Python、chu slots、inheritance和class变量==>属性是只读错误

2024-10-01 15:35:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个有成百上千个节点的大树,我使用__slots__来减少内存消耗。我刚发现了一个非常奇怪的错误并修复了它,但我不明白我看到的行为。在

下面是一个简化的代码示例:

class NodeBase(object):
    __slots__ = ["name"]
    def __init__(self, name):
        self.name = name

class NodeTypeA(NodeBase):
    name = "Brian"
    __slots__ = ["foo"]

然后执行以下操作:

^{pr2}$

如果没有定义NodeTypeA.name,则没有错误(旁注:该属性是错误的,并且没有理由存在)。因此,{cd3>也没有定义过。在

我不明白的是:为什么超类中存在类变量会干扰在子类的槽中设置实例变量?在

有人能解释为什么这种组合会导致object attribute is read-only错误吗?我知道我的例子是人为设计的,在真实的程序中不太可能是有意的,但这并没有使这种行为变得不那么奇怪。在

谢谢,
乔纳森


Tags: 内存代码nameself示例节点定义object
1条回答
网友
1楼 · 发布于 2024-10-01 15:35:22

一个较小的例子:

class C(object):
    __slots__ = ('x',)
    x = 0

C().x = 1

documentation on slots在某一点上表示:

__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__时,插槽属性的属性分配需要经过为插槽属性创建的描述符。隐藏子类中的描述符会导致Python无法找到设置属性所需的例程。但是Python仍然可以看到一个属性在那里(因为它找到了隐藏描述符的对象),因此它报告属性是只读的。在

相关问题 更多 >

    热门问题