![](/img/trans.png)
[英]Python super: calling a base class method which contains another base class method that is overriden by derived class
[英]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
的“叶子”定义。 由于self
是testB
的实例,因此调用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.