[英]How do I call the overwritten method of the child class instead of the parent class method?
[英]Python parent class init call child's overwritten method
请查看下面的示例代码。 父类需要调用setup()
函数,但是该函数需要在子类中定义/覆盖。 但是下面的示例代码显示,当child
初始化并调用super()
,super的方法将调用不包含任何内容的父setup()
。
预期的行为是实例化子级时,它使用super()
调用父级的__init__
并自动调用子级中定义的安装函数。 将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'
你是不是要求Human
的__init__
从child
S' __init__
。
super()
为您提供了一个调用超类方法的句柄,但是您需要通过对super()
方法调用来实现。
在这种情况下:
class Child(Human):
def __init__(self):
super().__init__()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.