Amaze UI Logo

码动指尖



python之__slots__限制对象属性

在python中,正常情况下,当我们定义了一个class,创建了一个class的实例后,我们可以给该实例绑定任何属性和方法,这就是动态语言的灵活性。


但是,如果我们想要限制class的属性怎么办?


这个时候 __slots__ 就登场了。


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


接下来进行实践:


>>> s = Student() # 创建新的实例
>>> s.name = 'Michael' # 绑定属性'name'
>>> s.age = 25 # 绑定属性'age'
>>> s.score = 99 # 绑定属性'score'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'Student' object has no attribute 'score'


由于'score'没有被放到__slots__中,所以不能绑定score属性,试图绑定score将得到AttributeError的错误。


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


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


除非在子类中也定义__slots__,这样,子类允许定义的属性就是自身的__slots__加上父类的__slots__


 Python

作者  :  奕弈

喵喵喵,你在心上



评论


About ME

about me

奕弈

为了最初的心,努力奋斗,从不懈怠的学习。

我不想成为一个庸俗的人。十年百年后,当我们死去,质疑我们的人同样死去,后人看到的是裹足不前、原地打转的你,还是一直奔跑、走到远方的我?

Contact ME