#超详细# Python “__slots__ ” 属性详解

1 简介

Python是动态语言,对于普通的类,可以为类实例赋值任何属性,这些属性会存储在__dict__中,但数据通过字典(Hash)存储所占用的空间较大,效率较低,__slots__属性的出现就是为了解决上述问题。
__slots__属性的作用是声明并限定类成员,并拒绝类创建__dict__和__weakref__属性以节约内存空间。

2 用法

>>> class Student(object):
...     __slots__ = ('name', 'age')
...     
>>> Abey = Student()
>>> Abey.name = 'Abey'
>>> Abey.gender = 'Female'
Traceback (most recent call last):
  File "<input>", line 1, in <module>
AttributeError: 'Student' object has no attribute 'gender'
>>> Abey.__dict__
Traceback (most recent call last):
  File "<input>", line 1, in <module>
AttributeError: 'Student' object has no attribute '__dict__'

3 继承树问题

__slots__在继承中有两种表现:

  1. 子类未声明__slots__时,不继承父类的__slots__,即此时子类实例可以随意赋值属性
  2. 子类声明__slots__时,继承父类的__slots__,即此时子类的__slots__为其自身+父类的__slots__
    以下面的父类为例:

参考

  1. Python官方文档
  2. Usage of slots?, Aaron Hall, Stack Overflow
发布了59 篇原创文章 · 获赞 2 · 访问量 4671

猜你喜欢

转载自blog.csdn.net/lch551218/article/details/104552245