首页 > 其他 > 详细

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

时间:2019-07-17 19:22:29      阅读:65      评论:0      收藏:0      [点我收藏+]

如果我们想要限制实例的属性怎么办?比如,只允许对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_。

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

原文:https://www.cnblogs.com/-chenxs/p/11203025.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!