Python是动态语言,任何实例在运行期都可以动态地添加属性。
如果要限制添加的属性,例如,Student类只允许添加 name、gender和score 这3个属性,就可以利用Python的一个特殊的__slots__来实现。
顾名思义,__slots__是指一个类允许的属性列表:
class Student(object): __slots__ = ('name', 'gender', 'score') def __init__(self, name, gender, score): self.name = name self.gender = gender self.score = score s=Student('Peter','male',99) s.age=28 print(s.age)
如果注销__slots__ = ('name', 'gender', 'score')
程序正常运行,为实例化对象添加age属性
如果添加__slots__属性,程序报错:
AttributeError: 'Student' object has no attribute 'age'
不允许添加slots列表内以外的属性
__slots__的目的是限制当前类所能拥有的属性,如果不需要添加任意动态的属性,使用__slots__也能节省内存。