In this article, let’s learn about the relevant knowledge about python__slots__. Some friends may have just come into contact with the python programming language and do not have a special understanding of this aspect. In the next article, we will Let me introduce you to the relevant knowledge about python__slots__.
What if we want to limit the properties of the instance? For example, only name and age attributes are allowed to be added to Student instances.
In order to achieve the purpose of restriction, Python allows you to define a special __slots__ variable when defining a class to limit the attributes that can be added to the class instance:
class Student(object): __slots__ = ('name', 'age') # 用tuple定义允许绑定的属性名称
Then, we try Try:
>>> 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'
Since 'score' is not placed in __slots__, the score attribute cannot be bound. If you try to bind score, you will get an AttributeError.
When using __slots__, please note that the attributes defined by __slots__ only affect the current class instance and have no effect on inherited subclasses:
>>> class GraduateStudent(Student): ... pass ... >>> g = GraduateStudent() >>> g.score = 9999
Unless it is also used in the subclass Define __slots__, so that the attributes that subclass instances are allowed to define are their own __slots__ plus the __slots__ of the parent class.
The above is all the content described in this article. This article mainly introduces the relevant knowledge of python__slots__. I hope you can use the information to understand the above content. I hope what I have described in this article will be helpful to you and make it easier for you to learn python.
For more related knowledge, please visit the Python tutorial column on the php Chinese website.
The above is the detailed content of What can __slots__ do in python? (Example analysis). For more information, please follow other related articles on the PHP Chinese website!