参考
概念
限制实例的属性, 比如,只允许对Student实例添加name和age属性。
class Student():
# 用tuple定义允许绑定的属性名称
__slots__ = ('name', 'age')
# 实例化Student
s1 = Student()
s1.name = 'allen'
s1.age = 22
s1.sex = 'male' # AttributeError: 'Student' object has no attribute 'sex'
由于'score'没有被放到__slots__中,所以不能绑定score属性,试图绑定score将得到AttributeError的错误。
_slots__定义的属性仅对当前类实例起作用;如果子类中没有_slots,对继承的子类是不起作用
class Student():
# 用tuple定义允许绑定的属性名称
__slots__ = ('name', 'age')
class GraduateStudent(Student):
pass
g = GraduateStudent()
g.score = 22 # it works
子类中也定义_slots_,这样,子类实例允许定义的属性就是自身的__slots__加上父类的_slots_
class Student():
# 用tuple定义允许绑定的属性名称
__slots__ = ('name', 'age')
class GraduateStudent(Student):
__slots__ = ()
g = GraduateStudent()
g.score = 22 #AttributeError: 'GraduateStudent' object has no attribute 'score'