![](/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.