Alb*_*ert 5 python recursion inheritance 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()
Run Code Online (Sandbox Code Playgroud)
我有这个输出:
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)
Run Code Online (Sandbox Code Playgroud)
提前致谢,
名称修改是完成这项工作的工具。在您的情况下,这看起来像这样:
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)
Run Code Online (Sandbox Code Playgroud)
链接文档的解释:
该形式的任何标识符
__spam(至少两个前导下划线,最多一个尾随下划线)在文本上都替换为_classname__spam,其中 classname 是删除了前导下划线的当前类名称。
| 归档时间: |
|
| 查看次数: |
957 次 |
| 最近记录: |