PHP前端开发

python里的__slots__能做什么?

百变鹏仔 3小时前 #Python
文章标签 能做什么

在这篇文章之中我们来了解一下关于python__slots__的相关知识,有些朋友可能是刚刚接触到python这一编程语言,对这一方面不是特别的了解,在接下来这篇文章将会来带大家来了解关于python__slots__的相关知识。

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

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

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

然后,我们试试:

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

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

立即学习“Python免费学习笔记(深入)”;

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

&gt;&gt;&gt; class GraduateStudent(Student):...     pass...&gt;&gt;&gt; g = GraduateStudent()&gt;&gt;&gt; g.score = 9999

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