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