为什么我的超类调用我的子类方法? [英] Why is my superclass calling my subclass method?

查看:63
本文介绍了为什么我的超类调用我的子类方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

When I call a method that was overrided from my constructor, I am getting an error and it says that it is missing an argument (due to the subclass requiring a second argument). However, I called the method in the super(), so why doesn't it call the super class version of that method?

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

This is best illustrated with a short example:

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'

好像是在调用B类中的do()方法,但是我想调用A类中的do()方法.理想情况下,代码应该打印:

It seems to be calling the do() method in class B, but I want to call the do() method in Class A. Ideally, the code should print:

A
A
B

我做错了什么?

推荐答案

答案是,一个基类调用了一个在自身上定义但又被子类覆盖的方法,调用了覆盖的方法子类不是基类上的方法.如需更多信息,请参阅从基类调用重写方法?.请参阅以下代码变体并遵循上述逻辑.

The answer is that a base class that calls a method that is defined on itself, but also overridden by a subclass, calls the overridden method on the subclass not the method on the base class. For further information see calling an overridden method from base class?. See the below variant of your code and follow the logic as described above.

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()

结果:一种乙一种乙

这篇关于为什么我的超类调用我的子类方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆