0
点赞
收藏
分享

微信扫一扫

极客编程python入门-slots功能


使用__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 条评论