Normally, 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. Define class First:
>>> class Student(object):... pass...
Then, try binding an attribute to the instance:
>>> s = Student()>>> s.name = ‘Michael‘ # 动态给实例绑定一个属性>>> print s.nameMichael
You can also try binding a method to an instance:
>>> def set_age(self, age): # 定义一个函数作为实例方法... self.age = age...>>> from types import MethodType>>> s.set_age = MethodType(set_age, s, Student) # 给实例绑定一个方法>>> s.set_age(25) # 调用实例方法>>> s.age # 测试结果25
However, the method that is bound to one instance does not work for another instance:
>>> s2 = Student() # 创建新的实例>>> s2.set_age(25) # 尝试调用方法Traceback (most recent call last): File "<stdin>", line 1, in <module>AttributeError: ‘Student‘ object has no attribute ‘set_age‘
To bind a method to all instances, you can bind the method to class:
>>> def set_score(self, score):... self.score = score...>>> Student.set_score = MethodType(set_score, None, Student)
When you bind a method to a class, all instances are callable:
>>> s.set_score(100)>>> s.score100>>> s2.set_score(99)>>> s2.score99
Typically, the above set_score method can be defined directly 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.
Using __slots__
But what if we want to restrict the properties of class? For example, only add and attributes to student instances are allowed name age .
For the purpose of limiting, Python allows you to define a special variable when defining a class __slots__ to limit the attributes that the class can add:
>>> class Student(object):... __slots__ = (‘name‘, ‘age‘) # 用tuple定义允许绑定的属性名称...
Then, let's try:
>>> s = Student() # 创建新的实例>>> s.name = ‘Michael‘ # 绑定属性‘name‘>>> s.age = 25 # 绑定属性‘age‘>>> s.score = 99 # 绑定属性‘score‘Traceback (most recent call last): File "<stdin>", line 1, in <module>AttributeError: ‘Student‘ object has no attribute ‘score‘
Because the property cannot be bound because it is ‘score‘ not placed __slots__ in, the score attempt to bind score will get attributeerror error.
It __slots__ is important to note that the __slots__ defined properties work only on the current class and do not work on inherited subclasses:
>>> class GraduateStudent(Student):... pass...>>> g = GraduateStudent()>>> g.score = 9999
Unless it is also defined in a subclass __slots__ , the subclass allows the defined property to be its own __slots__ plus the parent class __slots__ .
Python uses __slots__