【发布时间】:2021-12-30 11:59:53
【问题描述】:
在一门关于多重继承的课程中,我遇到了这段漂亮的代码。
class First(object):
def __init__(self):
super(First, self).__init__()
print("first")
class Second(object):
def __init__(self):
super(Second, self).__init__()
print("second")
class Third(Second,First):
def __init__(self):
super(Third, self).__init__()
print("third")
Third();
输出:
first
second
third
我有点害怕,所以我开始研究为什么这些东西还能奏效。我发现a lovely article about this matter 很好地解释了super 背后的机制。
然后我开始玩代码,我发现大部分代码实际上是多余的。我一步一步地修剪东西,直到只剩下这个可怜的骨架。
class First():
def __init__(self):
super().__init__()
print("first")
class Second():
def __init__(self):
super().__init__()
print("second")
class Third(Second,First):
def __init__(self):
super().__init__()
print("third")
Third();
这会产生完全相同的输出。现在对于object,我知道这可以省略,因为所有类都派生自基类object。那里没有问题。但是我不太明白传递给super 方法的参数背后的内容。所以我做了最后的调整来检查这是否也能正常工作:
class First():
def __init__(self):
super().__init__()
print("first")
class Second():
def __init__(self):
super().__init__()
print("second")
class Third(Second,First):
def __init__(self):
super(self).__init__()
print("third")
Third();
输出:
TypeError: super() argument 1 must be type, not Third
我可以理解self 在这种情况下指的是Third。在super(Third,self) 的情况下,Third 指的是一个类,它足以作为我认为的类型。那么在调用super 方法时,总是隐含所有这些冗余部分是否正确?除了我已经找到的链接之外,还有人有关于这些机制的一些很酷的文档吗?似乎它们被调用的顺序与列出类参数的顺序相反。
反转为class Third(First,Second) 给出输出:
second
first
third
我们将不胜感激。
【问题讨论】:
-
superwith arguments 是 python 2 的原始形式,新的无参数形式来自 python 3:python.org/dev/peps/pep-3135 -
这实际上是编译器的特殊情况。虽然它只是语法糖
-
顺便说一句,即使是括号在类定义上也是多余的:
class First:。分号也是如此。
标签: python multiple-inheritance