每个类在实例化时都会被分配一个dict,通过 实例.__dict__来访问,dict记录了实例的所有属性

如:

class Man(object):
pass

man = Man()
print(man.__dict__) # 输出的结果是 {}
man.name = 'Hel'
man.length = '152'
print(man.__dict__) # 输出的结果是 {'name': 'Hel', 'length': '152'}

变量__slots__是class从object继承的一个属性,用来定义类的可以绑定的属性,当在类中定义了__slots__之后,这个类就只能拥有定义的属性,同时该类的实例不能分配__dict__.

class Man(object):
__slots__ = ('age', 'length', 'name')

print(man.__dict__) # 输出AttributeError: 'Man' object has no attribute '__dict

类的实例只能有slots定义的属性,如果使用定义之外的属性,将会报错

class Man(object):
__slots__ = ('age', 'length', 'name')

man = Man()
man.name = 'Hel'
man.length = '152'
man.gender = 'male' # 输出AttributeError: 'Man' object has no attribute 'gender'

 

一般情况下,使用__slots__的类需要直接继承(object)

在继承自己创建的类时,不会继承__slots__属性

 

相关文章:

  • 2021-10-08
  • 2021-12-14
  • 2021-06-18
  • 2021-06-02
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-12-18
  • 2021-06-02
  • 2022-01-02
  • 2021-10-01
  • 2021-07-16
相关资源
相似解决方案