Python super: base class method calls another method

这一生的挚爱 提交于 2019-12-11 11:35:04

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/25097205/python-super-base-class-method-calls-another-method

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!