#Coding=utf-8" "when we define a class and create an instance of class, we can bind any property and method to that instance, which is the flexibility of dynamic language." " fromTypesImportMethodtypeclassStudent (object):PassdefSet_age (self, Age): Self.age= Ageif __name__=='__main__': S=Student () s.name='Michael' #dynamically binding an attribute to an instanceS.set_age = Methodtype (Set_age, s)#binding a method to an instance Print(s.name) s.set_age (25) Print(s.age)#The method that is bound to one instance does not work for another instance:Student.set_age = Methodtype (Set_age, Student)#To bind a method to all instances, you can bind the method to class:S1 =Student () s1.set_age (25) Print(S1.age)
- Restricted dynamic binding
#Coding=utf-8" "when we define a class and create an instance of class, we can bind any property and method to that instance, which is the flexibility of dynamic language." "classStudent (object):#What if we want to restrict the properties of an instance? For example, the name and age attributes are only allowed to be added dynamically on student instances. __slots__= ('name',' Age')#Define a property name that allows binding by using a tuple classgraduatestudent (Student):Passif __name__=='__main__': S=Student () s.name='lky'S.age= 25#S.score = Print(S.name, S.age)#__slots__-defined properties work only on the current class instance and do not work on inherited subclasses, unless __SLOTS__ is also defined in the subclass, so that the subclass instance allows the defined property to be its own __slots__ plus the __slots__ of the parent class. g =graduatestudent () G.score= 100G.name='MCs'G.age= 26Print(G.name, G.age, G.score)
python-dynamic binding of classes and objects (properties, methods)