从层次结构中的顶级类调用方法而不是覆盖 [英] Call method from top class in hierarchy instead of override

查看:53
本文介绍了从层次结构中的顶级类调用方法而不是覆盖的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有类 Base(object)Derived(Base).它们都实现了一个函数 fooDerived.foo 覆盖了 Base 中的版本.

Let's say I have classes Base(object) and Derived(Base). These both implement a function foo, with Derived.foo overriding the version in Base.

但是,在其中一种方法中,比如 Base.learn_to_foo,我想调用 Base.foo 而不是派生版本,无论它是否被覆盖.所以,我在该方法中调用 Base.foo(self) :

However, in one of the methods, say Base.learn_to_foo, I want to call Base.foo instead of the derived version regardless of whether it was overridden. So, I call Base.foo(self) in that method:

class Base(object):
    # ...

    def learn_to_foo(self, x):
        y = Base.foo(self, x)
        # check if we foo'd correctly, do interesting stuff

这种方法似乎有效,而且从领域的角度来看,它完全有道理,但不知何故,它闻起来有点可疑.这是要走的路,还是应该重构?

This approach seems to work and from a domain standpoint, it makes perfect sense, but somehow it smells a bit fishy. Is this the way to go, or should I refactor?

推荐答案

答案是使用 super() 函数.您这样做的方式完全正确,因为您不想调用在超类中重写的虚拟方法.由于您似乎一直都希望基类的确切实现,唯一的方法是获取基类的 unbound 方法对象,将其绑定到 self,即可以是 BaseDerived 的实例.使用明确提供的 self 调用未绑定的方法,因为第一个参数会返回一个 bound 方法.从现在开始,Base.foo 将作用于实例 self 的数据.这是完全可以接受的,也是 Python 处理非虚拟方法调用的方式.这是 Python 允许您做而 Java 不能做的一件好事.

The answer is NOT to use the super() function. The way you are doing is exactly right as you don't want to invoke the virtual method that is overridden in the super class. Since you seem to want the base class' exact implementation all the time, the only way is to get the base class' unbound method object back, bound it to self, which could be an instance of Base or Derived. Invoke the unbound method with self supplied explicitly as the first parameter gives you back a bound method. From this point forward, Base.foo will be acting on the instance self's data. This is perfectly acceptable and is the way Python deals with non-virtual method invocation. This is one of the nice things that Python allows you to do that Java does not.

这篇关于从层次结构中的顶级类调用方法而不是覆盖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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