使用_slots_变量限制class实例能添加的属性

如果我们想要限制实例的属性怎么办?比如,只允许对Student实例添加nameage属性。

那么我们在Student类里面增添_slots_变量

例如:

class Student(object):
    __slots__ = ('name', 'age') # 用tuple定义允许绑定的属性名称

然后,我们试试:

>>> 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'

当我们为s实例添加score属性时,就发生了报错,那么_slots_变量的限制就成功了。因为’score‘属性没有被放到_slots_中。

注意:__slots__定义的属性仅对当前类实例起作用,对继承的子类是不起作用的,除非在子类中也定义_slots_。

posted @ 2019-07-17 18:58  ctrl_TT豆  阅读(285)  评论(0编辑  收藏  举报