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

Jam*_*ang 5 python inheritance overriding subclass superclass

当我调用从构造函数重写的方法时,出现错误,提示缺少参数(由于子类需要第二个参数)。但是,我在 super() 中调用了该方法,那么为什么它不调用该方法的超类版本呢?

用一个简短的例子可以很好地说明这一点:

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()
Run Code Online (Sandbox Code Playgroud)

这是我得到的错误:

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'
Run Code Online (Sandbox Code Playgroud)

看起来是调用B类中的do()方法,但我想调用A类中的do()方法。理想情况下,代码应该打印:

A
A
B
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

see*_*per 5

答案是,调用在自身定义但也被子类重写的方法的基类会调用子类上的重写方法,而不是基类上的方法。有关更多信息,请参阅从基类调用重写的方法?。请参阅以下代码变体并遵循上述逻辑。

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()
Run Code Online (Sandbox Code Playgroud)

结果:A B A B