简体   繁体   English

为什么在使用__slots__时默认删除__weakref__?

[英]Why is __weakref__ removed by default when __slots__ is used?

I think the main purpose of __slots__ is to save the memory usage by allowing to specify properties explicitly, instead of using __dict__ allowing dynamic property assignment on the instances. 我认为__slots__的主要目的是通过允许显式指定属性来节省内存使用,而不是使用允许在实例上进行动态属性赋值的__dict__ So I somehow understand why __dict__ is removed by default when using __slots__ . 所以我在某种程度上理解为什么在使用__slots__时默认删除了__dict__ But why does it meanwhile remove __weakref__ by default? 但是为什么同时默认删除__weakref__

Reference: https://docs.python.org/3/reference/datamodel.html#slots 参考: https//docs.python.org/3/reference/datamodel.html#slots

I can't read minds, but I suspect the rationale goes like this: 我无法读懂思想,但我怀疑理由是这样的:

  1. If __weakref__ wasn't disabled by default when using __slots__ , providing a way to save the associated memory explicitly would require yet another special opt-out mechanism 如果在使用__slots__时默认没有禁用__weakref__ ,那么提供一种明确保存相关内存的方法还需要另一种特殊的退出机制
  2. More special cases add complexity to the language, and this one would provide no real benefit 更多特殊情况增加了语言的复杂性,而这种情况并没有带来真正的好处

Given how infrequently weak references are used at all, it was probably deemed simpler to simpler have it disabled by default, with the option to opt back in. 鉴于根本不常使用弱引用,默认情况下禁用它可能更简单,可以选择重新加入。

Diving to implementation details, in a sense, unslotted user-defined classes have precisely two "slots" (one for __dict__ , one for __weakref__ ) over and above the base object header, so having __slots__ say "Replace the default with this explicit list" makes it natural to remove both __dict__ and __weakref__ when __slots__ comes into play. 潜水到实现细节,从某种意义上说,未开槽的用户定义的类在基础对象标题之上有正好两个“槽”(一个用于__dict__ ,一个用于__weakref__ ),所以让__slots__说“用这个显式列表替换默认值”当__slots__发挥__weakref__时,自然地删除__dict____weakref__

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM