sandyp
sandyp

Reputation: 432

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?

Upvotes: 1

Views: 626

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121406

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.

Upvotes: 4

Related Questions