Python 从父调用扩展子方法

Python calling extended child method from parent

我正在尝试调用父方法,然后在 python 中调用父 class 的扩展子方法。

目标:创建一个继承父类的子方法。在 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 中你可以先调用 Parent 与 super(Child, self).method_a() 一切都会好起来的!

# 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() 方法)

parent class 不应该依赖或需要有关 child class 的知识。但是,您可以对 child class 强加 要求 以实现特定方法。

class Parent:
    def __init__(self):
        print('Init parent')
        self.method_a()

    def method_a(self):
        print('parent method')
        self.method_a_callback()


    # The child should override this to augment
    # the behavior of method_a, rather than overriding
    # method_a entirely.
    def method_a_callback(self):
        pass


class Child(Parent):
    def method_a_callback(self):
        print('child method')