当我从派生类调用基类递归方法时,递归调用是针对派生方法而不是基类方法完成的。我如何在不修改基类实现的情况下(在示例类 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/