【问题标题】:Inherit class with weakref in slots在插槽中继承带有弱引用的类
【发布时间】:2014-08-15 23:16:05
【问题描述】:

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

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。

【问题讨论】:

    标签: python inheritance weak-references


    【解决方案1】:

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

    实际上错误说:

    TypeError: 调用元类基时出错 __weakref__ slot disallowed:要么我们已经有一个,要么__itemsize__ != 0

    简单使用:

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

    这在__slots__的文档中有解释:

    __slots__ 声明的作用仅限于它所在的类 被定义为。因此,子类将具有__dict__,除非它们 还定义__slots__只能包含任何附加的名称 插槽)。

    【讨论】:

    • 谢谢,就是这样。如何处理派生类中的插槽在文档中有些隐藏,所以我没有找到。
    猜你喜欢
    • 1970-01-01
    • 2022-01-23
    • 2021-08-23
    • 2018-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-10
    相关资源
    最近更新 更多