面向对象 __slots__

使用__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'

由于‘score’没有被放到__slots__中,所以不能绑定score属性,会报错!

注意:使用__slots__定义的属性只对当前类实例中起作用,对继承的子类不起作用!

注意:

除非在子类中也定义__slots__ , 这样子子类实例允许定义的属性就是自身的__slots__ 和父类的__slots__

发布了41 篇原创文章 · 获赞 29 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/weixin_43930694/article/details/104530517