python的类class中,限制属性__slots__函数的用法

为了到达限制的目的,class在定义的时候,允许一个特殊的__slots__变量,来限制该class实例能够添加的属性

1 >>>class Student(object):
2      __slots__ = ("name", "age")  ###用tuple定义允许绑定的属性名称
3 
4 >>>s = Student()
5 >>>s.name = "micheal"
6 >>>s.age = 28
7 >>>s.score = 99
8 会抛出AttributeError: "Student " object has no attribute "score"

使用__slots__要注意,该变量定义的属性仅对当前类实例起作用,

对继承的子类是不起作用的。

 

posted @ 2017-09-21 20:39  遗世独立的愚公  阅读(352)  评论(0编辑  收藏  举报