在创建class类之后,如:
class Student(object):
pass
随后,创建Student实例,表示为:
>>> s = Student()
>>> s.name = 'Michael' # 动态给实例绑定一个属性
>>> print(s.name)
Michael
可以尝试给实例绑定一个方法,采用MethodType:
>>> def set_age(self, age): # 定义一个函数作为实例方法
... self.age = age
...
>>> from types import MethodType
>>> s.set_age = MethodType(set_age, s) # 给实例绑定一个方法
>>> s.set_age(25) # 调用实例方法
>>> s.age # 测试结果
25
对一个实例绑定方法,对另一个实例是不起作用的,因此可以对类绑定方法,为:
>>> def set_score(self, score):
... self.score = score
...
>>> Student.set_score = MethodType(set_score, Student)
__slots__限制实例的属性
为了达到限制的目的,Python允许采用__slots来限制类的属性:
>>> def set_score(self, score):
... self.score = score
...
>>> Student.set_score = MethodType(set_score, Student)
然后,我们试试:
>>> 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'
由于'score'没有被放到__slots__中,所以不能绑定score属性,试图绑定score将得到AttributeError的错误。
使用__slots__要注意,__slots__定义的属性仅对当前类实例起作用,对继承的子类是不起作用的