簡體   English   中英

Python超級:基類方法調用另一個方法

[英]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).f2Base類上找到下一個f2方法,並將其綁定到self 然后,在調用self時, self仍然是同一實例,並且對self調用f1將調用Derived.f1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM