python - Python混淆中的多重继承
问题描述
我有以下实现多重继承的代码。我希望调用super(base2,self).__init__()
打印--> "Printing from base2".
但是程序什么也没打印;它也不会引发错误。
class base1:
def __init__(self):
print("printing from base1")
def method(self,val):
print("From method of base1", val)
class base2:
def __init__(self):
print("printing from base2")
def method(self,val):
print("From method of base2", val)
class child(base1, base2):
def __init__(self):
super(base2,self).__init__() #is not working as expected
x = child()
解决方案
The call to super
expects the child class as its first param, not the base class. You should be doing
super(child, self).__init__()
However, since python 3.0, you can simply do
super().__init__()
But how does this play into multiple inheritence? Well that's extremely well explained in this answer
Basically, in your case, changing super
to the appropriate call will yield the base1
class' __init__
call. According to the MRO (method resolution order).
What if you wanted to invoke the __init__
of base2
? Well you're looking into directly calling base2.__init__()
in that case, or simply changing the order of inheritance.
class child(base2, base1):
def __init__(self):
super().__init__()
Now this will print the base2
class' __init__
method
推荐阅读
- django - 使用 Django 和 Gitlab CI/CD 时如何从 .env 文件中设置变量?
- java - 如何为自定义 SWT-Column-Ratio-Layout 编写 JUnit 测试?
- javascript - 如何在 JSON 中编写 Mathjax 公式并放入 HTML?
- web - 同一页面上的多个 websocket
- python - 是否总是需要在 Python 代码中有 __init__ (构造函数)?什么时候变得不可或缺?
- python - tkinter 中按钮大小的浮点数
- java - 如何通过合并在 IDEA 中运行 Sbt?
- python-3.x - 安装包时在 Jupyter notebook 中输入确认信息
- mysql - 概念混淆:在 GCP 中与 Wordpress 的云交互以及与 Spring 的 APP 交互
- c# - 为 Azure 服务总线会话处理器设置 WaitTimeOut