Python从paren调用扩展子方法

2024-06-16 10:29:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试调用一个父方法,然后调用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()方法)


Tags: to方法代码self功能childinitdef
1条回答
网友
1楼 · 发布于 2024-06-16 10:29:07

父类不应依赖或要求有关子类的知识。但是,您可以将要求施加到子类上,以实现某个方法。在

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')

相关问题 更多 >