python class objects and instance objects dynamically add method of share
- 2020-06-19 11:00:14
- OfStack
Examples are as follows:
class Person():
def __init__(self, name):
self.name = name
def print_name(self):
print(self.name)
p = Person('Li')
import types
p.print_name = types.MethodType(print_name, p) # Bind a function to an object
p.print_name()
@staticmethod
def print_abc():
print('abc')
Person.print_abc = print_abc
Person.print_abc()
@classmethod
def print_123(cls):
print('123')
Person.print_123 = print_123
Person.print_123()