极客编程python入门-slots功能

阅读 133

2022-12-27


使用__slots__


如果我们想要限制实例的属性怎么办?比如,只允许对Student实例添加​name​​age​属性。


class Student(object):
__slots__ = ('name', 'age') # 用tuple定义允许绑定的属性名称


极客编程python入门-slots功能_python


使用__slots__要注意,__slots__定义的属性仅对当前类实例起作用,对继承的子类是不起作用的:


>>> class GraduateStudent(Student):
... pass
...
>>> g = GraduateStudent()
>>> g.score = 9999

精彩评论(0)

0 0 举报