问题:
Python中如何限制class属性
方案:
Python中可以通过__slots__变量来限制class属性
使用方式:
class Person: __slots__ = ['name', 'age'] class Student(Person): pass class Doctor(Person): __slots__ = []
如上,当Person通过__slots__限制属性只能为name和age后,Person实例则不能再绑定其他属性。
if __name__ == '__main__': person = Person() student = Student() doctor = Doctor() person.sex = 'male' student.sex = 'male' doctor.sex = 'male'
- person绑定sex属性时,执行代码报错:AttributeError: 'Person' object has no attribute 'sex'
- student绑定sex属性时,代码执行正常,因为__slots__定义的属性只对当前类有效,对继承的子类无效
- 如果继承的子类也定义了__slots__,则子类允许定义的属性就是自身的__slots__加上父类的__slots__,因此 doctor.sex='male'执行报错:AttributeError: 'Doctor' object has no attribute 'sex'