【发布时间】:2019-07-18 20:28:27
【问题描述】:
我正在尝试调用父方法,然后是 python 中父类的扩展子方法。
目标:创建一个继承父级的子方法。在 Parent 的 init 中,它调用它自己的方法之一。父方法应该做一些事情,然后调用相同方法(同名)的子版本来扩展功能。永远不会直接调用同名的子方法。这适用于 python 2.7
绝对最坏的情况我可以添加更多的 kwargs 来修改 Parent method_a 的功能,但我宁愿让它更抽象。下面的示例代码。
def Parent(object):
def __init__(self):
print('Init Parent')
self.method_a()
def method_a():
print('parent method')
# potentially syntax to call the Child method here
# there will be several Child classes though, so it needs to be abstract
def Child(Parent):
def __init__(self):
super(Child).__init__(self)
def method_a():
print('child method')
obj = Child()
# expected output:
'Init Parent'
'parent method'
'child method'
谢谢!
编辑:chepner 的回答确实有效(并且可能更正确),但我用来测试的代码是错误的,而且这种行为在 python 中确实有效。 Python 将调用 Child 的 method_a 函数而不是 Parent 函数,然后在 Child 的 method_a 中,您可以先使用 super(Child, self).method_a() 调用 Parent,一切都会正常工作!
# with the same parent method as above'
def Child(Parent):
def method_a():
# call the Parent method_a first
super(Child, self).method_a()
print('child method')
c = Child()
# output:
'Init parent'
'parent method'
'child method'
这可行,但 chepner 的方法可能仍然更正确(在 Parent 中使用抽象的 method_a_callback() 方法)
【问题讨论】:
标签: python inheritance parent-child multiple-inheritance