python - 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'
解决方案
您不是从's调用Human
's的。__init__
child
__init__
super()
为您提供调用超类方法的句柄,但您需要通过方法调用来实现super()
。
在这种情况下:
class Child(Human):
def __init__(self):
super().__init__()
推荐阅读
- python - NLTK - 从概率上下文无关语法 (PCFG) 生成文本
- c - 从c中的电话簿代码中删除联系人
- html - 如何本地化 thymeleaf 输入 type=submit 对象?
- java - 如何将 RecyclerView 添加到父活动中的约束布局?
- docker - 使用带有命名卷的 docker swarm
- java - 使用单个 Jar 编译项目和 Renjin 时 Jar 文件未运行?
- svg.js - svg.js v3 和 svg.panzoom.js 不适用于汇总(也不适用于 webpack/parcel)
- http-headers - 如何从 HttpClient 请求中删除 Content-Type 和 User-Agent 标头?
- java - Java Retrofit2 POST JsonObject 的好习惯?
- r - 设置种子并复制 100 次