gpt4 book ai didi

python - 在插槽中使用 weakref 继承类

转载 作者:太空宇宙 更新时间:2023-11-03 14:23:17 24 4
gpt4 key购买 nike

我尝试在我的类上使用弱引用,我在其中使用插槽来节省一些内存,但我无法创建派生类。

class A(object):
__slots__ = ['__weakref__']

class B(A):
__slots__ = A.__slots__ + ['foo']
#TypeError: Error when calling the metaclass bases
# __weakref__ slot disallowed: either we already got one, or __itemsize__ != 0

技巧在哪里?我没有找到任何解决方案。我正在使用 python 2.7.3。

最佳答案

在派生类中,您不应该放置在基类中定义的插槽。

实际上错误说:

TypeError: Error when calling the metaclass bases __weakref__ slot disallowed: either we already got one, or __itemsize__ != 0

只需使用:

class B(A):
__slots__ = ['foo']

__slots__ 的文档对此进行了解释:

The action of a __slots__ declaration is limited to the class where it is defined. As a result, subclasses will have a __dict__ unless they also define __slots__ (which must only contain names of any additional slots).

关于python - 在插槽中使用 weakref 继承类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24407874/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com