【发布时间】:2020-10-27 02:59:01
【问题描述】:
我在 Python 3.8 中有两个类:A 和 B,其中 B 继承自 A,两个类都有同名的方法,因此 B 类的方法覆盖 A 类的方法,B 中的方法有一个参数加号。
B中的函数调用super().method(condition),A中的函数递归调用self.method(condition),我期望的结果是当我做super ().method(condition)在B中,然后self.method(condition)在A中再次执行A类的方法,但是得到的结果是它试图执行B 中的方法,由于缺少参数而引发错误。 这是代码:
class A():
def method(self, condition):
if condition:
print('from A')
else:
self.method(True)
class B(A):
def method(self, condition, other):
if condition:
print('from B')
else:
super().method(False)
b = B()
b.method(False, 0)
这是错误:
TypeError: method() 缺少 1 个必需的位置参数:'other'
【问题讨论】:
-
Python 正在做它应该做的事情。
object.method()调用适用于object的方法版本。从哪里调用它并不重要。如果您使用类型为 `B 的对象调用它,那么它将调用 B 的方法实现。
标签: python recursion inheritance polymorphism