python之__slots__
使用__slots__来限制实例的属性。
例如:
class person:
def setName(self,name):
self.name=name
person1=person()
person1.name = "512bit"
person1.age = 12
print(person1.age)
print(person1.name)
输出为:
12
512bit
Process finished with exit code 0
当使用__slots来限制属性只有’name’, 'gender’时,
class person:
__slots__ = ('name', 'gender')
def setName(self,name):
self.name=name
person1=person()
person1.name = "tian"
person1.age = 12
print(person1.age)
print(person1.name)
提示 AttributeError: ‘person’ object has no attribute 'age‘。
但要注意的是,slots__定义的属性仅对当前类实例起作用,对继承的子类是不起作用的。除非在子类中也定义__slots,这样,子类实例允许定义的属性就是自身的__slots__加上父类的__slots__。