python中的__solots__方法

__slots__可以用来限制实例对象所能添加的属性.当添加的属性不在__slots__的声明里面就会抛出AttributeError异常.

>>> class Person(object):
__slots__ = ("name", "age")
>>> P = Person()
>>> P.name = "Tom"
>>> P.age = 20
>>> P.score = 100
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
AttributeError: Person instance has no attribute 'score'

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




原文地址:https://www.cnblogs.com/fanlei5458/p/9235482.html