Home > Backend Development > Python Tutorial > What can __slots__ do in python? (Example analysis)

What can __slots__ do in python? (Example analysis)

乌拉乌拉~
Release: 2018-08-22 17:06:53
Original
1328 people have browsed it

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定义允许绑定的属性名称
Copy after login

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: &#39;Student&#39; object has no attribute &#39;score&#39;
Copy after login

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
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template