python - 覆盖python中的递归方法

标签 python inheritance recursion overriding

当我从派生类调用基类递归方法时,递归调用是针对派生方法而不是基类方法完成的。我如何在不修改基类实现的情况下(在示例类 A 中)避免这种情况?

举个例子

class A(object):
    # recursive method
    def f(self, x):
        print x,
        if x < 0:
            self.f(x+1)
        if x > 0:
            self.f(x-1)
        if x == 0:
           print ""

class B(A):
   # Override method 
   def f(self):
       # do some pretty cool stuff
       super(B, self).f(25)

if __name__ == "__main__":
    A().f(5)
    B().f()

我得到了这个输出:

5 4 3 2 1 0 
25
Traceback (most recent call last):
  File "./test.py", line 19, in <module>
     B().f()
  File "./test.py", line 15, in f
     super(B, self).f(25)
   File "./test.py", line 9, in f
     self.f(x-1)
  TypeError: f() takes exactly 1 argument (2 given)

提前致谢

最佳答案

Name mangling是这项工作的工具。在您的情况下,这看起来像这样:

class A(object):
    # recursive method
    def f(self, x):
        print x,
        if x < 0:
            self.__f(x+1)
        if x > 0:
            self.__f(x-1)
        if x == 0:
           print ""

    __f = f

class B(A):
   # Override method 
   def f(self):
       # do some pretty cool stuff
       super(B, self).f(25)

链接文档中的解释:

Any identifier of the form __spam (at least two leading underscores, at most one trailing underscore) is textually replaced with _classname__spam, where classname is the current class name with leading underscore(s) stripped.

关于python - 覆盖python中的递归方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6846829/

相关文章:

python - 使用 Beautiful Soup 查找跨度中的部分类名

python - 如何在具有不同请求的另一个列表中查找列表

Java递归查找图上的所有路径

javascript - html5 canvas pacman 游戏 - javascript 太多递归

c++ - 具有非类型模板参数的多态性

python - 如何使用递归计算整数的长度

python - 尝试在非包中进行相对导入

python - 如何制作双线性插值生成的等高线图的动画?

php - Symfony2-Doctrine2 继承仍然无法正常工作

javascript - 使用下划线继承