为什么我的超类调用我的子类方法?

Why is my superclass calling my subclass method?

当我调用从我的构造函数覆盖的方法时,我收到一个错误,它说它缺少一个参数(由于 subclass 需要第二个参数)。但是,我在 super() 中调用了该方法,那么为什么它不调用该方法的超级 class 版本?

最好用一个简短的例子来说明:

class A:
    def __init__(self):
        self.do()

    def do(self):
        print("A")


class B(A):
    def __init__(self):
        super().__init__()
        self.do("B")

    def do(self, arg2):
        super().do()
        print(arg2)


b = B()

这是我得到的错误:

Traceback (most recent call last):
    File "D:/Python/Advanced/randomStuff/supersub.py", line 19, in <module>
        b = B()
    File "D:/Python/Advanced/randomStuff/supersub.py", line 11, in __init__
        super().__init__()
    File "D:/Python/Advanced/randomStuff/supersub.py", line 3, in __init__
        self.do()
TypeError: do() missing 1 required positional argument: 'arg2'

好像是调用classB中的do()方法,但我想调用ClassA中的do()方法。 理想情况下,代码应打印:

A
A
B

我做错了什么?

这真的很好奇。我没有解决方案,但以下内容似乎按预期工作。它完全相同,除了 super() 是用 self.class 作为参数显式调用的,我认为这是隐式的。

也许更熟练的 Pythonista 可以基于此观察。

class A:
    def __init__(self):
        self.do()

    def do(self):
        print("A")

class B(A):
    def __init__(self):
        super(self.__class__).__init__()
        self.do("B")

    def do(self, arg2):
        super().do()
        print(arg2)

print('***init A***')
a = A()
print('***init B***')
b = B()
print('***A.do()***')
a.do()
print('***B.do()***')
b.do('test')

答案是基 class 调用在自身上定义的方法,但也被子 class 覆盖,调用子上的 覆盖方法class 不是基于 class 的方法。有关详细信息,请参阅 calling an overridden method from base class?。请参阅以下代码变体并遵循上述逻辑。

class A:
    def __init__(self):
        self.do()

    def do(self):
        print("do A")


class B(A):
    def __init__(self):
        super().__init__()
        self.do()

    def do(self):
        super().do()
        print("do B")


b = B()

结果: 一种 乙 一种 B