Python super:基类方法调用另一个方法 [英] Python super: base class method calls another method

查看:45
本文介绍了Python super:基类方法调用另一个方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用 Python super 时遇到了这种意外行为,所以我想我会问.我知道基本的 super 用法,但希望有人在这里详细说明我的问题.考虑代码:

class Base(对象):def f1(自己):打印 'Base f1'def f2(自我):打印 'Base f2'self.f1()派生类(基础):def f1(自己):打印派生的 f1"def f2(自我):打印派生的 f2"超级(派生,自我).f2()

对 Derived().f2() 的调用导致:

派生的 f2基数 f2派生 f1

我相当期待:

派生的 f2基数 f2基数 f1

Base.f2() 中的调用self.f1()"不应该导致 Base.f1() 被调用吗?

解决方案

self 在所有情况下都是仍然是Derived 实例.>

super() 找到覆盖的方法并将其绑定到self,你不是换出类.super(Derived, self).f2Base 类上找到下一个 f2 方法,并将其绑定到 self>.然后调用时,self 仍然是同一个实例,在self 上调用f1 将调用Derived.f1.

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.

这篇关于Python super:基类方法调用另一个方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆