我尝试调用一个父方法,然后调用python中父类的扩展子方法。在
目标:创建继承父级的子方法。在父级的init中,它调用自己的一个方法。父方法应该做些事情,然后调用相同方法(同名)的子版本来扩展功能。永远不会直接调用同名的子方法。这是针对python2.7的
绝对最坏的情况下,我可以添加更多的kwargs来修改父方法的功能,但我更希望它更抽象。下面是示例代码。在
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'
谢谢!在
编辑:切普纳的答案确实有效(可能更正确),但我用来测试的代码是错误的,这种行为在python中确实有效。Python将调用Child的方法_一个函数而不是父方法,然后在Child的方法_a中,您可以先用super(Child,self)调用父方法,然后一切都会正常工作!在
^{pr2}$这是可行的,但chepner的方法可能仍然更正确(在Parent中使用抽象方法\u a_callback()方法)
父类不应依赖或要求有关子类的知识。但是,您可以将要求施加到子类上,以实现某个方法。在
相关问题 更多 >
编程相关推荐