一、动态添加属性
>>> class Student(object):
pass >>> st = Student()
>>> st.name = 'Jack'
>>> st.name
'Jack'
二、动态给实例添加方法
>>> from types import MethodType
>>> class Student(object):
pass >>> def set_age(self, age):
self.age = age >>> st.set_age = MethodType(set_age, st) # 给实例绑定一个方法
>>> st.set_age(25)
>>> st.age
25
三、动态给类添加方法
>>> class Student(object):
pass >>> def set_score(self, score):
self.score = score >>> Student.set_score = set_score
>>> s1 = Student()
>>> s1.set_score(100)
>>> s1.score
100
>>> s2 = Student()
>>> s2.set_score(50)
>>> s2.score
50
四、限制实例的属性 __slots__
>>> class Student(object):
__slots__ = ('name', 'age') # 用tuple定义允许绑定对的属性名称 >>> s = Student()
>>> s.name = 'Jack'
>>> s.age = 20
>>> s.score = 100
Traceback (most recent call last):
File "<pyshell#53>", line 1, in <module>
s.score = 100
AttributeError: 'Student' object has no attribute 'score'
__slots__
定义的属性仅对当前类实例起作用,对继承的子类是不起作用的:
>>> class GraduateStudent(Student):
... pass
...
>>> g = GraduateStudent()
>>> g.score = 9999
除非在子类中也定义__slots__
,这样,子类实例允许定义的属性就是自身的__slots__
加上父类的__slots__:
>>> class GraduateStudent(Student):
__slots__ = ('score', ) >>> g = GraduateStudent()
>>> g.score = 100
>>> g.name = 'Mike'
>>> g.age = 10
>>> g.other = 'abc'
Traceback (most recent call last):
File "<pyshell#69>", line 1, in <module>
g.other = 'abc'
AttributeError: 'GraduateStudent' object has no attribute 'other'