【问题标题】:Python3 redefine a class: super still calls old classPython3重新定义一个类:super仍然调用旧类
【发布时间】:2022-01-09 08:40:19
【问题描述】:

这段代码:

class a:
    def __init__(self):
        print("a here")

class b(a):
    def __init__(self):
        print("b here")
        super().__init__()

B = b()

class a:
    def __init__(self):
        print("NEW a here")

BB = b()

产生这个输出:

b here
a here
b here
a here

为什么?

如果我将 b 类中的 super().init() 更改为 a.init(self),它可以正常工作。

【问题讨论】:

    标签: python-3.x class redefinition


    【解决方案1】:

    我认为这是因为类 b 仍然从您定义的原始类 a 继承。 您可以通过打印出 a 类的 id 来检查这一点

    id(a)
    id(b.__bases__[0])
    

    【讨论】:

      【解决方案2】:

      b 持有对其基类的引用。该引用是在创建类时创建的,而不是稍后在调用 super 时按名称查找。因此,您看到的“不正确”行为实际上是预期的行为。要更改 b 视为其基类的类,您还需要重新定义 b

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-02-16
        • 1970-01-01
        • 1970-01-01
        • 2015-08-14
        • 1970-01-01
        相关资源
        最近更新 更多