您的位置:首页 > 其它

使用 __slots__

2016-05-27 17:14 323 查看
动态添加类的属性跟方法:
属性:
class Student(object):
pass

s = Student()
s.name = 'Michael'
print(s.name)

方法:
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

使用 __slots__
class Student(object):
__slots__ = ('name', 'age')

>>> 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__
定义的属性仅对当前类实例起作用,对继承的子类是不起作用的:
>>> class GraduateStudent(Student):...     pass
...
>>> g = GraduateStudent()
>>> g.score = 9999


除非在子类中也定义
__slots__
,这样,子类实例允许定义的属性就是自身的
__slots__
加上父类的
__slots__
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: