[英]Python super: calling a base class method which contains another base class method that is overriden by derived class
[英]Python super: base class method calls another method
我使用Python super
遇到了這種意外行為,所以我想問一下。 我知道基本的super
用法,但希望有人在這里詳細說明我的問題。 考慮一下代碼:
class Base (object):
def f1 (self):
print 'Base f1'
def f2 (self):
print 'Base f2'
self.f1()
class Derived (Base):
def f1 (self):
print 'Derived f1'
def f2 (self):
print 'Derived f2'
super(Derived, self).f2()
調用Derived()。f2()會導致:
Derived f2
Base f2
Derived f1
我當時很期待:
Derived f2
Base f2
Base f1
Base.f2()中的“ self.f1()”調用是否應該導致Base.f1()被調用?
在所有情況下, self
仍是Derived
實例 。
super()
查找重寫的方法並將其綁定到self
,而不是交換類。 super(Derived, self).f2
在Base
類上找到下一個f2
方法,並將其綁定到self
。 然后,在調用self
時, self
仍然是同一實例,並且對self
調用f1
將調用Derived.f1
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.