Using _slots_
Under normal circumstances, when you define a class and create an instance of class, you can bind any property and method to the instance, which is the flexibility of dynamic language. Define class First:
class Student (object): Pass
Then, try binding an attribute to the instance:
>>> s = Student ()'Michael'print s.namemichael
You can also try binding a method to an instance:
def set_age (self,age): = age fromimport methodtype>>> s.set_age = Methodtype (set_age, s)>>> s.set_age (+)>>> s.age
However, a method bound to one instance does not work for another instance:
>>> S1 =Student ()>>> S1.name ='Jack'>>>S1.name'Jack'>>> S1.set_age (24) Traceback (most recent): File"<pyshell#18>", Line 1,inch<module>S1.set_age (24) Attributeerror:'Student'object has no attribute'Set_age'>>>
To bind a method to all instances, you can bind the method to class:
>>> student.set_age = set_age>>> s1.set_age >>> s1.age
Typically, the Set_age method above can be directly defined in class, but dynamic binding allows us to dynamically add functionality to class while the program is running, which is difficult to implement in a static language.
But what if you really want to restrict the properties of an instance? Only add the name and age attributes to the student instance.
For the purpose of limiting, Python allows you to define a special _slots_ variable when defining a class to limit the attributes that the class instance can add:
>>classStudent (object):__slots__= ('name',' Age') >>> s =Student ()>>> S.score = 99Traceback (most recent): File"<pyshell#34>", Line 1,inch<module>S.score= 99Attributeerror:'Student'object has no attribute'score'>>>
Unless __slot__ is also defined in a subclass, the class instance allows the defined property to be itself __slots__ plus the __slot__ of the parent class
Python object-oriented advanced programming-_slots_