class Student(object):
pass
s = Student()
s.name = 'Michael'
print(s.name)
Michael
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
s2 = Student()
s2.set_age(25)
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-17-c8243b1832b5> in <module>
1 s2 = Student()
----> 2 s2.set_age(25)
AttributeError: 'Student' object has no attribute 'set_age'
尝试给另外的实例也绑定该方法,但是报错了
为了给所有实例绑定方法,直接绑定给class
def set_score(self,score):
self.score = score
Student.set_score = set_score
s.set_score(100)
s.score
100
s2.set_score(90)
s2.score
90
但是我们要限制实例属性该怎么办?比如只允许添加name和age属性
class Student1(object):
__slots__ = ('name','age')
s3 = Student1()
s3.name ='Michael'
s3.age = 25
s3.score = 88
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-24-2069d6e5cbf8> in <module>
2 s3.name ='Michael'
3 s3.age = 25
----> 4 s3.score = 88
AttributeError: 'Student1' object has no attribute 'score'
由于’score’没有放到__slots__中,所以不能绑定score属性
注意:__slots__定义的属性仅对当前类的实例起作用,对继承的子类是不起作用的