After an instance is created using class in the Dynamic Language, You can bind any method and attribute to the instance.
Class student (object): pass # bind an attribute S = student () s. name = 'Michael '# dynamically bind an attribute print (S. name) def set_age (self, age): # define a function as the instance (called a member in Java) method self. age = age # bind a method from types import methodtypes to student. set_age_new = methodtype (set_age, S) # bind a method s to the instance. set_age_new (25) # Call the instance method print (S. age) # Test Result # But the binding method does not work for other instances S2 = student () # create a new instance # attributeerror: 'Student 'object has no attribute 'set _ age_new '# s2.set _ age_new (23) # Call the bound instance method # to bind a method to all instances, you can bind the def set_score (self, socres) to the class: Self. socrestudent. set_score_new = set_score # bind method to class # After binding, all instances can call S. set_score_new (100) print (S. socres) s2.set _ score_new (99) print (s2.socres)
Michael2510099
Generally, the set_score () method is directly defined in the class, but dynamic binding adds a function to the class when the program is allowed to run, which is difficult to implement in static languages.
__slots__
If you want to restrict attributes, for example, the value can be added to student instances.
name
And
age
Attribute. To achieve this purpose, Python defines a special variable when defining the class.
__slots__
To restrict the attributes that can be added to a class instance.
Class student (object): _ slots _ = ('name', 'age') # Use tuple to define the property name s = student () for running the binding () # create a new instance S. name = 'Michael '# bind the attribute names. age = 25 # bind the attribute age # attributeerror: 'student 'object has no attribute 'score '# S. score = 99 # tips: when defining _ slots _, note that this attribute takes effect for the instance of the current class and does not take effect for the inherited subclass class graduatestudent (student ): passg = graduatestudent () g. score = 9999
Unless it is defined in the subclass
__slots__
The properties defined for running subclass instances are their own
__slots__
Add the parent class
__slots__
_ Slots _ consumption Method