Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/322.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 为什么我的超类调用我的子类方法?_Python_Inheritance_Overriding_Subclass_Superclass - Fatal编程技术网

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

Python 为什么我的超类调用我的子类方法?,python,inheritance,overriding,subclass,superclass,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(

当我调用从构造函数重写的方法时,我得到一个错误,它说它缺少一个参数(由于子类需要第二个参数)。但是,我在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()
以下是我得到的错误:

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'

我做错了什么?

这真的很奇怪。我没有一个解决方案,但下面的方法似乎按预期工作。除了super()被self显式调用之外,它是完全相同的。class作为参数,我认为它是隐式的

也许一个更熟练的蟒蛇学家可以在这一观察的基础上进一步发展

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 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()
结果: A. B A. B

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