为了限制实例的属性,可以在定义class的时候,定义一个特殊的__slots__变量,来限制class实例能添加的属性。
比如,只允许对Persion实例添加name 和 age 属性

class Person(object):
__slots__ = ("name", "age")

P = Person()
P.name = "老王"
P.age = 20
P.score = 100 # AttributeError: 'Person' object has no attribute 'score'


class Test(Person):
pass

t = Test()
t.score = 100
注意 :__slots__定义的属性仅对当前类实例起作用,对继承的子类是不起作用的

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-12-23
  • 2021-09-02
  • 2021-11-25
  • 2021-09-14
  • 2021-12-11
  • 2022-12-23
猜你喜欢
  • 2021-09-19
  • 2021-11-09
  • 2021-11-01
  • 2022-12-23
  • 2022-01-16
  • 2021-05-19
相关资源
相似解决方案