【发布时间】:2023-03-24 03:49:02
【问题描述】:
对于 Python 新手,谁能告诉我这里发生了什么?为什么要打印“A init”?
如果我从__init__ 类B 的函数中删除super().__init__() 行,则行为符合预期。但是为什么下面的代码没有错误,我虽然B 没有超类??
class A:
def __init__(self):
print("A init")
class B:
def __init__(self):
super().__init__() # why is this line not an error
print("B init")
class C(B, A):
def __init__(self):
super().__init__()
print("C init")
c = C()
输出
A init
B init
C init
Process finished with exit code 0
【问题讨论】:
-
在python 3中所有类都继承自
object。 -
我明白了。但是当我调用 C 的构造函数时,为什么它打印“A init”,我在想根据 MRO 规则它只会打印“B init”,因为它解析为“最左边的类”?看来 B 的 init 函数正在调用 A 的 init 函数。
-
我认为C同时调用A和B,多重继承
-
嗯。根据我的理解,C 应该调用它自己的 init 函数(如果已定义),并且在我的代码中,当我在 C 的 init 中调用 super() 的 init 时,它应该调用 B 的 init,因为 B 是优先级的“超类”(最左边) 因为它 C 被定义为 C(B,A)
-
顺便说一句,你可以使用这个在线工具来可视化代码执行pythontutor.com/visualize.html#mode=edit
标签: python