This article mainly shares with you a method for dynamically adding python class objects and instance objects. It has great reference value and I hope it will be helpful to everyone. Let’s follow the editor to take a look, I hope it can help everyone.
The example is 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) # 绑定函数到对象 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()
Related recommendations:
How to dynamically add styles to the HTML tags returned by Ajax
Using jQuery to dynamically add small ads Detailed explanation
The above is the detailed content of Dynamically add methods to python class objects and instance objects. For more information, please follow other related articles on the PHP Chinese website!