Python day 9 (1) dynamically bind attributes and methods to the instance, pythonday
I. The slots method is not used (all added outside the class after the class is defined ):
(1) dynamic attribute binding
class Student(object):
pass
>>> S = Student () >>> s. name = 'Michael '# dynamically bind an attribute to the instance >>> print (s. name) Michael
(2) dynamic binding method
>>> Def set_age (self, age): # define a function as an instance method... self. age = age... >>> from types import MethodType >>> s. set_age = MethodType (set_age, s) # bind a method to the instance> s. set_age (25) # Call the instance method> s. age # Test Result 25
Note: The method bound to one instance does not work for another instance.
(3) bind methods to all instances (BIND methods to class)
def set_score(self, score):... self.score = score...>>> Student.set_score = set_score
Ii. Use _ slots _ to restrict instance attributes
For example, the restricted attribute is 'name' and 'age' only'
Class Student (object): _ slots _ = ('name', 'age') # Use tuple to define the names of attributes that can be bound
Use__slots__Note,__slots__The defined attribute only takes effect on the current class instance and does not take effect on the inherited subclass.