繁体   English   中英

使用super时,基类方法将调用Derived类方法。 很迷茫

[英]Base class method calling the Derived class method when using super. Very confused

这对我来说似乎很混乱。 有人可以解释为什么这种未知的神奇事物发生了吗?

class A(object):
    def testA(self):
        print "TestA of A"
        self.testB()

    def testB(self):
        print "TestB of A"

class B(A):
    def testA(self):
        super(B, self).testA()
        print "TestA of B"
        self.testB()

    def testB(self):
        print "TestB of B"

if __name__ == '__main__':
    test = B()
    test.testA()
Program Output:
    ===============
    TestA of A
    TestB of B --> Why it is calling derived class method ?
    TestA of B
    TestB of B

    Expected Output:
    ================
    TestA of A
    TestB of A -- I want to see A here.
    TestA of B
    TestB of B

您的回答将不胜感激。 谢谢。

A.testA ,您调用self.testB 这意味着为当前实例调用testB的“叶子”定义。 由于selftestB的实例,因此调用B.testB

即使您在类A上定义的方法中编写了self.testB ,这也不意味着它将调用类A上定义的方法的版本。 您正在实例上调用方法,并且在运行时动态确定实例的类,实例上定义的任何方法都将运行。 由于实例类的B和类B覆盖testA ,实例的版本testA是由提供的一个B

如果要在A.testA中调用A.testB ,则必须通过调用A.testB(self)来明确地做到这一点。 但是,您应该考虑为什么要这样做。 重写方法的全部目的是使您可以更改类的操作方式。 A不需要知道哪个版本的testB被调用。 它只需要知道它正在调用一个名为testB的方法,该方法就可以执行程序/库中记录的方法testB 如果A特别要求调用其自己的testB方法,则子类很难更改testB的行为,因为A将忽略其替代并继续调用其自己的版本。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM