1.1 使用__slots__
1.1.1 类方法的绑定
实例上添加方法
>>> class Student(object):
... pass
...
>>> def set_age(self, age): #定义函数作为实例方法,注意self参数
... self.age = age
...
>>> s = Student()
>>> fromtypes import MethodType
>>> s.set_age= MethodType(set_age, s) #给实例s添加方法set_age
>>> s.set_age(24)
>>> s.age
24
>>> s1 = Student()
>>> s1.set_age(24) --注意其他实例不能调用
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: ‘Student‘ object has noattribute ‘set_age‘
给类绑定方法—动态增加类的方法
>>> defset_score(self, score):
... self.score = score
...
>>>Student.set_score = set_score
>>> s.set_score(98)
>>> s.score
98
>>> s1.set_score(100)
>>> s1.score
100
1.1.2 使用__slots__
作用限制实例的属性。
>>> class Student(object):
... __slots__ = (‘name‘, ‘age‘) #用tuple限制属性名称
...
>>> s = Student()
>>> s.name = ‘daidai‘
>>> s.name
‘daidai‘
>>> s.score = 100
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: ‘Student‘ object has noattribute ‘score‘
注意__slots__只对当前类实例起作用
>>> class Gstudent(Student):
... pass
...
>>> g = Gstudent()
>>> g.score = 98 --子类仍然可以定义
>>> g.score
98
子类加上__slots__就可同时限制父类和子类的属性名称
>>> class Gstudent(Student):
... __slots__ = (‘score‘, ‘grade‘)
... pass
...
>>> g = Gstudent()
>>> g.unslot=898
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: ‘Gstudent‘ object has noattribute ‘unslot‘
>>> g.name = ‘daidai‘
>>> g.name
‘daidai‘