简体   繁体   中英

Python super: base class method calls another method

I came across this unexpected behavior using Python super , so I thought I would ask. I am aware of basic super usage but would like someone to elaborate more on my problem here. Consider the code:

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()

The call to Derived().f2() results in:

Derived f2
Base f2
Derived f1

I was rather expecting:

Derived f2
Base f2
Base f1

Shouldn't the call "self.f1()" in Base.f2() result in Base.f1() being called?

self in all cases is still the Derived instance .

super() finds the overriden method and binds it to self , you are not swapping out classes. super(Derived, self).f2 finds the next f2 method on the Base class, and binds that to self . When called then, self is still the same instance, and calling f1 on self will invoke Derived.f1 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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