[英]Python parent class init call child's overwritten method
Please take a look at the sample code below. 请查看下面的示例代码。 The parent class, needs to call the
setup()
function, but that function needs to be defined/overwritten in the child class. 父类需要调用
setup()
函数,但是该函数需要在子类中定义/覆盖。 But the sample code below shows that when child
is initialized and called super()
, the super's method calls the parent setup()
which contains nothing. 但是下面的示例代码显示,当
child
初始化并调用super()
,super的方法将调用不包含任何内容的父setup()
。
Intended behavior is when child is instantiated, it calls parent's __init__
by using super()
and automatically call the setup function defined in the child. 预期的行为是实例化子级时,它使用
super()
调用父级的__init__
并自动调用子级中定义的安装函数。 Setting Human.setup()
as abstract class also did not seem to work. 将
Human.setup()
设置为抽象类似乎也不起作用。
Google can only find information on how to call parent's method from child, but this case is the reverse, "How to call child's method from parent". Google只能找到有关如何从子级调用父级方法的信息,但这种情况恰恰相反,即“如何从父级调用父级方法”。 Or is it not possible in python3?
还是在python3中不可能?
The reason it needs to call the setup function of the child is due to each child class will be having a different setup procedure. 之所以需要调用子级的设置函数,是因为每个子级将具有不同的设置过程。 But they share most of the methods defined in the parent class.
但是它们共享父类中定义的大多数方法。
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'
You are not calling Human
's __init__
from child
's __init__
. 你是不是要求
Human
的__init__
从child
S' __init__
。
super()
gives you a handle through which to call superclass methods, but you need to do that via method calls on super()
. super()
为您提供了一个调用超类方法的句柄,但是您需要通过对super()
方法调用来实现。
In this case: 在这种情况下:
class Child(Human):
def __init__(self):
super().__init__()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.