使用super进行Python递归方法调用

Max*_*Max 3 python super

我正在使用依赖于递归方法调用的库:

class A(object):
    def __init__(self):
        self.foo = None

    def f(self):
        if not self.foo:
            print("Hello")
            self.foo = 100
            self.f()
Run Code Online (Sandbox Code Playgroud)

我想在使用原始实现时覆盖方法f():

class B(A):
    def f(self):
        super(B, self).f()
        print("World")
Run Code Online (Sandbox Code Playgroud)

这样,我希望得到:

Hello
World
Run Code Online (Sandbox Code Playgroud)

相反,我看到:

Hello
World
World
Run Code Online (Sandbox Code Playgroud)

我理解这是因为A类中的原始代码调用self.f(),它找到了B.self.

问题:使用"超级(B,自我).f()"将自我视为A类,递归调用Af(),然后返回Bf()打印"World?"的最Pythonic方法是什么?

谢谢.

Mar*_*ers 5

我能看到这项工作的唯一方法是A.f()不使用self.f()而是使用A.f(self).

更好的设计是A.f()将递归调用委托给单独的方法:

class A(object):
    def __init__(self):
        self.foo = None

    def f(self):
        self._f_recursive()

    def _f_recursive(self):
        if not self.foo:
            print("Hello")
            self.foo = 100
            self._f_recursive()
Run Code Online (Sandbox Code Playgroud)

如果你唯一的选择在于B,那么除了不要覆盖f()之外,就是暂时在课堂上撒谎.这不是Pythonic或推荐但它会起作用:

class B(A):
    def f(self):
        try:
            self.__class__, cls = A, self.__class__
            A.f(self)
        finally:
            self.__class__ = cls
        print("World")
Run Code Online (Sandbox Code Playgroud)

要明确这一点:这不是线程安全的,也不是解决这个问题的正确方法.