1.__ slots__属性

__ slots__ allow us to explicitly declare data members (like properties) and deny the creation of __ dict__ and __ weakref__ (unless explicitly declared in __ slots__ or available in a parent.)
The space saved over using __ dict__ can be significant.
object.__ slots__
This class variable can be assigned a string, iterable, or sequence of strings with variable names used by instances. __ slots__ reserves space for the declared variables and prevents the automatic creation of __ dict__ and __ weakref__ for each instance.

1.1__ slots__是一个类变量允许我们在不创建实例的属性字典__ dict__的情况下定义属性; 这种方法适用于属性较少而实例很多的情况,可以节省实例 字典占用的内存空间. 类变量可以赋值为字符串, 可迭代对象或具有实例使用的变量名的字符串序列(???)

由于这种方法创建的实例没有属性字典, 因此无法创建在slots变量规定以外的属性.例如:

class Tests1:__slots__ = ['name', 'age']def shit(self):print('shit')t1 = Tests1()
print(Tests1.__dict__)  # 类字典依然存在
t1.name = 'sabi'
#t1.gender = 'male'  # 不可新增属性
#print(t1.__dict__)  # 实例属性字典不存在
print(t1.name)#result
{'__module__': '__main__', '__slots__': ['name', 'age'], 'shit': <function Tests1.shit at 0x0000022ABA3E99D8>, 'age': <member 'age' of 'Tests1' objects>, 'name': <member 'name' of 'Tests1' objects>, '__doc__': None}
sabi
class Tests1:__slots__ = ['name', 'age']def __init__(self, height):  self.height = height  # 不在slots中实例无法初始化
1.2当父类没有使用__ slots__而子类有slots时,子类实例的属性字典永远可以访问

•When inheriting from a class without __ slots__, the __ dict__ and __ weakref__ attribute of the instances will always be accessible.

实例:

class Test0:def ppt(self):print('ppt')class Tests1(Test0):__slots__ = ['name', 'age']def shit(self):print('shit')t1 = Tests1()
print(Tests1.__dict__)
t1.name = 'sabi'
t1.gender = 'male'
print(t1.__dict__)
print(t1.name)#result
{'__module__': '__main__', '__slots__': ['name', 'age'], 'shit': <function Tests1.shit at 0x000002C69A999A60>, 'age': <member 'age' of 'Tests1' objects>, 'name': <member 'name' of 'Tests1' objects>, '__doc__': None}
{'gender': 'male'}
sabi
1.3当父类有slots而子类没有时, 子类可继承父类的slots属性,但子类依然存在属性字典__ dict__

•The action of a slots declaration is not limited to the class where it is defined. slots declared in parents are available in child classes. However, child subclasses will get a dict and weakref unless they also define slots (which should only contain names of any additional slots).

实例:

class Tests1:__slots__ = ['name', 'age']def shit(self):print('shit')class Test2(Tests1):height = '175't2 = Test2()
t2.name = 'sabi2'  # 属性name并没有被加入字典,而是存在slots中
t2.gender = 'male' # 属性gender被加入属性字典
print(t2.__dict__)   # 但子类有属性字典
print(t2.__slots__)  # 子类可继承父类的slots属性
1.4当子类和父类中都定义了slots属性时,会优先寻找子类的slots属性,父类的slots属性依然可以指定,但如果变量重名,则父类属性不可访问.

•If a class defines a slot also defined in a base class, the instance variable defined by the base class slot is inaccessible (except by retrieving its descriptor directly from the base class). This renders the meaning of the program undefined. In the future, a check may be added to prevent this.
•如果类定义了也在基类中定义的槽,则基类槽定义的实例变量不可访问(除非直接从基类检索其描述符)。 这使得程序的含义未定义。 将来,可能会添加一项检查以防止这种情况发生。

class Tests1:__slots__ = ['name', 'age']def shit(self):print('shit')class Test2(Tests1):__slots__ = ['a123','b456', 'age']height = '175't2 = Test2()
t2.name = 'sabi2'  # 但依然可以指定父类的slots值
t2.age = '28'
print(t2.__slots__)  # 只寻找自己的slot
print(t2.name, t2.age)#result
['a123', 'b456', 'age']
sabi2 28
1.5其他

1)•Nonempty __ slots__ does not work for classes derived from “variable-length” built-in types such as int, bytes and tuple.
•非空__ slots__不适用于从“可变长度”内置类型派生的类,如int,bytes和tuple

2)•Any non-string iterable may be assigned to __ slots__. Mappings may also be used; however, in the future, special meaning may be assigned to the values corresponding to each key.
•可以将任何非字符串的可迭代对象分配给__ slots__。 也可以使用映射; 但是,将来可以为与每个键对应的值分配特殊含义。

3)__ class__ assignment works only if both classes have the same __ slots__.
__class__赋值仅在两个类具有相同__slots__时有效。

3)实例:

class Test0:__slots__ = ['abc','def']def ppt(self):print('ppt')class Tests1:__slots__ = ['abc','def']age = '222't1 = Tests1()
print(t1.__class__)
t1.__class__ = Test0
print(t1.__class__)#result
<class '__main__.Tests1'>
<class '__main__.Test0'>

4)•Multiple inheritance with multiple slotted parent classes can be used, but only one parent is allowed to have attributes created by slots (the other bases must have empty slot layouts) - violations raise TypeError.
具有多slots的父类的多继承也可以使用,但只有一个父类允许有slots创建的属性,其他父类必须时空的slots, 否则会引起TypeError.

4)实例:

class Test0:__slots__ = ['abc','def']def ppt(self):print('ppt')class Tests1:__slots__ = []def shit(self):print('shit')class Test2(Tests1,Test0):# __slots__ = ['a123','b456', 'age']height = '175't2 = Test2()
t2.abc = 'fuck'
print(t2.__slots__)#result
[]

5)•Without a __ dict__ variable, instances cannot be assigned new variables not listed in the __ slots__ definition. Attempts to assign to an unlisted variable name raises AttributeError. If dynamic assignment of new variables is desired, then add ‘__ dict__’ to the sequence of strings in the __ slots__ declaration.
•如果没有__ dict__变量,则无法为实例分配__ slots__定义中未列出的新变量。 尝试分配slots中没有变量名称会引发AttributeError。 如果需要动态分配新变量,则将“__ dict__”添加到__ slots__声明中的字符串序列中。

6)•Without a __ weakref__ variable for each instance, classes defining __ slots__ do not support weak references to its instances. If weak reference support is needed, then add ‘__ weakref__’ to the sequence of strings in the __ slots__ declaration.
•如果没有每个实例的__ werefref__变量,则定义__ slots__的类不支持对其实例的弱引用。 如果需要弱引用支持,则将“__ weakref__”添加到__ slots__声明中的字符串序列。

6)__ slots__ are implemented at the class level by creating descriptors (Implementing Descriptors) for each variable name. As a result, class attributes cannot be used to set default values for instance variables defined by __ slots__; otherwise, the class attribute would overwrite the descriptor assignment.
__ slots__是通过为每个变量名创建描述符(实现描述符)在类级别实现的。 因此,类属性不能用于为__ slots__定义的实例变量设置默认值; 否则,class属性将覆盖描述符赋值。

python关于类的slots属性相关推荐

  1. python的类里的属性是否可以为列表_Python中如何获取类属性的列表

    前言 最近工作中遇到个需求是要得到一个类的静态属性,也就是说有个类 Type ,我要动态获取 Type.FTE 这个属性的值. 最简单的方案有两个: getattr(Type, 'FTE') Type ...

  2. python的类里的属性是否可以为列表_是否有Python方法可以访问类的所有非私有和非内置属性?...

    我想调用一种方法给我一个所有"非私有"的词典(我在这里使用"私有"一词,因为它在 Python中并不存在)和非内置属性(即那些在类上不要以单个或双下划线开头.像 ...

  3. python:小心类实例的属性动态绑定机制

    为什么80%的码农都做不了架构师?>>>    class Test:def __init__(self):self.__key='init'def get_key(self):re ...

  4. Python自定义类中定义属性的两种方式

    封面图片:<Python程序设计开发宝典>,ISBN:9787302472100,董付国,清华大学出版社 图书详情:https://item.jd.com/12143483.html 京东 ...

  5. python五十九: slots属性

    class Foo:__slots__ = ['name', 'age']f = Foo() print(f.__slots__) print(Foo.__slots__) f.name = 'dsf ...

  6. python 元类工厂模式_Python进阶丨如何创建你的第一个Python元类?

    摘要:通过本文,将深入讨论Python元类,其属性,如何以及何时在Python中使用元类. Python元类设置类的行为和规则.元类有助于修改类的实例,并且相当复杂,是Python编程的高级功能之一. ...

  7. 如何创建你的第一个Python元类?

    Python元类设置类的行为和规则.元类有助于修改类的实例,并且相当复杂,是Python编程的高级功能之一.通过本文,将深入讨论Python元类,其属性,如何以及何时在Python中使用元类.本文介绍 ...

  8. Python进阶丨如何创建你的第一个Python元类?

    摘要:通过本文,将深入讨论Python元类,其属性,如何以及何时在Python中使用元类. Python元类设置类的行为和规则.元类有助于修改类的实例,并且相当复杂,是Python编程的高级功能之一. ...

  9. 【python进阶】类的__slots__属性

    python作为一门动态语言,可以在对象创建后动态的添加属性和方法. 示例1:动态添加属性 class Dog(object):def __init__(self, name, age):self.n ...

最新文章

  1. Ubuntu Linux系统下apt-get命令详解
  2. 系统运维包括哪些内容_智能养老系统包括哪些?养老管理系统内容详解
  3. arduino 读取当前时间_Arm难以撼动,暴露下的Arduino与RISCV联合体就是个笑话
  4. 关于相对布局RelativeLayout的各种属性介绍
  5. java 写jsp_Java开发之JSP指令
  6. 酷炫的深色模式APP设计模板|2020设计潮流趋势
  7. 伦理的陷阱:人工智能与虚拟现实
  8. entry在java的用处_JAVA问题:Map.Entry的一般用处是什么?
  9. 【论文解读】UniLM:一种既能阅读又能自动生成的预训练模型
  10. Lync server 2013新建持久聊天室提示用户未启用SIP
  11. Android Studio 开发JNI应用
  12. 面试--拼多多面试--后台开发实习生
  13. 经验分布函数(Empirical Distribution Functions)
  14. ps盖印图层在哪里_PS盖印图层快捷键
  15. layui标签输入框inputTags
  16. 细述微信浏览器打不开文件下载链接的几种解决方案
  17. 服务器cadence比虚拟机慢,Cadence版本选择浅见
  18. python 根据坐标点计算方位角函数
  19. SQLite安装与使用 (Linux)
  20. esp8266与mega2560开发板串口通信

热门文章

  1. 自学web前端觉得好难,可能你遇到了这些困境
  2. Jupyter Notebook的简单使用
  3. 推荐几款适用于物联网的开源数据库
  4. 综合业务数字网调制解调器的全球与中国市场2022-2028年:技术、参与者、趋势、市场规模及占有率研究报告
  5. Java基础入门笔记2
  6. 微信小程序的登录逻辑
  7. Dota2一直 正在登录服务器的解决办法
  8. 没有钱 想创业 怎么办
  9. linux 查看服务器磁盘类型
  10. 以ChatGPT模型开发一个学习英语的超级助手