Python从父级调用扩展子方法

Python从父级调用扩展子方法,python,inheritance,parent-child,multiple-inheritance,Python,Inheritance,Parent Child,Multiple Inheritance,我试图调用一个父方法,然后调用python中父类的扩展子方法 目标:创建继承父方法的子方法。在父级的init中,它调用自己的一个方法。父方法应该做一些事情,然后调用同一方法(同名)的子版本来扩展功能。永远不会直接调用同名的子方法。这是针对Python2.7的 绝对最坏的情况我可以添加更多的Kwarg来修改父方法_a的功能,但我更希望它更抽象。下面是示例代码 def父对象(对象): 定义初始化(自): 打印('Init Parent') self.method_a() def方法_a(): 打印(

我试图调用一个父方法,然后调用python中父类的扩展子方法

目标:创建继承父方法的子方法。在父级的init中,它调用自己的一个方法。父方法应该做一些事情,然后调用同一方法(同名)的子版本来扩展功能。永远不会直接调用同名的子方法。这是针对Python2.7的

绝对最坏的情况我可以添加更多的Kwarg来修改父方法_a的功能,但我更希望它更抽象。下面是示例代码

def父对象(对象):
定义初始化(自):
打印('Init Parent')
self.method_a()
def方法_a():
打印('父方法')
#此处调用子方法的潜在语法
#不过会有几个子类,所以它需要是抽象的
def子级(父级):
定义初始化(自):
超级(子)。\uuuuu初始\uuuuuuuuu(自我)
def方法_a():
打印('子方法')
obj=Child()
#预期产出:
“初始化父级”
“父方法”
“子方法”
谢谢

编辑:切普纳的回答确实有效(可能更正确),但我用来测试的代码是错误的,这种行为在python中确实有效。Python将调用Child的方法而不是父方法,然后在Child的方法中,您可以首先使用super(Child,self)调用父方法。方法a()一切都会正常工作

#使用与上述相同的父方法'
def子级(父级):
def方法_a():
#首先调用父方法\u a
super(Child,self).method_a()
打印('子方法')
c=儿童()
#输出:
“初始化父级”
“父方法”
“子方法”

这是可行的,但是chepner的方法可能仍然更正确(在父类中有一个抽象方法\u a_callback()方法)

父类不应该依赖或需要关于子类的知识。但是,您可以对子类施加要求以实现某个方法

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

父类不应该依赖于或需要关于子类的知识。但是,您可以对子类施加要求以实现某个方法

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

啊,好的,这应该很有效。谢谢你的反馈!啊,好的,这应该很有效。谢谢你的反馈!