Binding properties and methods to an instance object:
1. Bind attributes to an instance: first define a student class
#!/usr/bin/pythonclass Student(object): pass
Then bind the properties:
s = Student()s.name = ‘AAA‘ # 动态给实例绑定一个属性print(s.name)#输出AAA
2, to the instance binding method: First define a method
def add(self,a,b): self.a = a self.b = b return self.a +self.b
Then bind the method:
When Methodtype binds a method to a class instance, each instance has its own point-of-reference area, which does not interfere with each other. Methodtype (method name, instance object)
from types import MethodTypes.add = MethodType(add,s)print(s.add(10,20))#输出30print(s.a)#输出10print(s.b)#输出20
Second, to the class binding method:
Using Methodtype to bind a method to a class is not to write the method directly inside the class, but rather to create a link to an external method in memory, and this link will be copied when the instance is created.
Methodtype (method name, class name)
Student.add = MethodType(add,Student)s2 = Student()print(s2.add(10,60))#输出70
#也可以把函数直接赋给类. xxx
Student.add = adds3 = Student()print(s3.add(10,60))#输出70
Python instance-determined properties and methods or class binding methods