我是Python的新手,这里的多态使我感到困惑。我有一个父类A,而类B从A继承。两者都定义了一个名为“ fibonacci”的函数,其中B.fibonacci是A.fibonacci的简单包装。
我原以为这很简单,但是,我得到了以下调试输出,这意味着,尽管从父类中调用了self.fibonacci,但parent始终倾向于child而不是parent。
================调试输出1 ===============
child fibonacci called!!! 5
parent fibonacci called!!! 5
child fibonacci called!!! 4
parent fibonacci called!!! 4
child fibonacci called!!! 3
parent fibonacci called!!! 3
child fibonacci called!!! 2
parent fibonacci called!!! 2
child fibonacci called!!! 1
parent fibonacci called!!! 1
child fibonacci called!!! 0
parent fibonacci called!!! 0
child fibonacci called!!! 1
parent fibonacci called!!! 1
child fibonacci called!!! 2
parent fibonacci called!!! 2
child fibonacci called!!! 1
parent fibonacci called!!! 1
child fibonacci called!!! 0
parent fibonacci called!!! 0
child fibonacci called!!! 3
parent fibonacci called!!! 3
child fibonacci called!!! 2
parent fibonacci called!!! 2
child fibonacci called!!! 1
parent fibonacci called!!! 1
child fibonacci called!!! 0
parent fibonacci called!!! 0
child fibonacci called!!! 1
================结束调试输出1 ===============
我后来使用了另一种方法来调用super: 返回(A.fibonacci(super(),n)* 100)
现在调试消息更加混乱:
================调试输出2 ===============
child fibonacci called!!! 5
parent fibonacci called!!! 5
parent fibonacci called!!! 4
child fibonacci called!!! 3
parent fibonacci called!!! 3
parent fibonacci called!!! 2
child fibonacci called!!! 1
parent fibonacci called!!! 1
child fibonacci called!!! 0
parent fibonacci called!!! 0
parent fibonacci called!!! 1
child fibonacci called!!! 2
parent fibonacci called!!! 2
parent fibonacci called!!! 1
parent fibonacci called!!! 0
parent fibonacci called!!! 3
child fibonacci called!!! 2
parent fibonacci called!!! 2
parent fibonacci called!!! 1
parent fibonacci called!!! 0
child fibonacci called!!! 1
parent fibonacci called!!! 1
================结束调试输出2 ===============
我知道我总是可以像这样在父实现中明确指定类名:
return (A.fibonacci(self, n-1) + A.fibonacci(self, n-2))
但是从软件维护的角度来看,总是知道将来我的类方法是否将被覆盖并在一开始使用A.(self,xx)
有什么意义?
class A:
def fibonacci(self, n:int) -> int:
print("parent fibonacci called!!! " + str(n))
if n <= 1:
return n
else:
return (self.fibonacci(n-1) + self.fibonacci(n-2))
# alternative implementation here
# return (A.fibonacci(self, n-1) + A.fibonacci(self, n-2))
pass
class B(A)
def fibonacci(self, n:int) -> int:
print("child fibonacci called!!! " + str(n))
return (super().fibonacci(n) * 100)
# alternative implementation here:
# return (A.fibonacci(super(), n) * 100)
pass
obj = B()
print(obj.fibonacci(5))