首页 > 解决方案 > Python父类init调用child的覆盖方法

问题描述

请看下面的示例代码。父类需要调用该setup()函数,但该函数需要在子类中定义/覆盖。但是下面的示例代码显示,当child被初始化和调用super()时,super 的方法调用了setup()不包含任何内容的 parent。

预期行为是当子实例化时,它__init__通过使用调用父级super()并自动调用子级中定义的设置函数。设置Human.setup()为抽象类似乎也不起作用。

Google 只能找到关于如何从子级调用父级方法的信息,但这种情况正好相反,“如何从父级调用子级方法”。还是在python3中不可能?

它需要调用子类的设置函数的原因是每个子类将具有不同的设置过程。但是它们共享父类中定义的大部分方法。

class Human(object):
    def __init__(self):
        self.setup()

    def setup(self):
        pass

class child(Human):
    def __init__(self):
        super()

    def setup(self):
        self.name = "test"

>>> A = child()
>>> A.name
    AttributeError: 'child' object has no attribute 'name'

标签: pythonpython-3.xoop

解决方案


您不是从's调用Human's的。__init__child__init__

super()为您提供调用超类方法的句柄,但您需要通过方法调用来实现super()

在这种情况下:

class Child(Human):
    def __init__(self):
        super().__init__()

推荐阅读