__slots__的作用

2018-03-23  本文已影响2人  i_promise
class Person(object):
    __slots__ = ('name', 'age')

p = Person()
p.name = 'aaa'
p.age = 11
p.sex = 'nn'
print(p.name,p.age,p.sex)

Traceback (most recent call last):
File "/Users/yjx/Desktop/yjx/slots的作用.py", line 20, in <module>
p.sex = 'nn'
AttributeError: 'Person' object has no attribute 'sex'

__slots__定义的属性仅对当前类实例起作用,对继承的子类是不起作用的
上一篇 下一篇

猜你喜欢

热点阅读