Python从父级调用扩展子方法

时间:2019-07-18 20:28:27

标签: python inheritance parent-child multiple-inheritance

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

目标:创建一个继承父对象的子方法。在父级的 init 中,它调用自己的方法之一。父方法应该执行某些操作,然后调用同一方法(具有相同名称)的子版本以扩展功能。同名的子方法永远不会直接调用。这是针对python 2.7

绝对的最坏情况是,我可以添加更多的kwarg来修改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()方法)

1 个答案:

答案 0 :(得分:2)

父类不应依赖或要求有关子类的知识。但是,您可以对子类施加 requirement 来实现某种方法。

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')
相关问题