我只是在深入研究一些更高级的 python 主题(嗯,至少对我来说是高级的)。我现在正在阅读有关多重继承以及如何使用 super() 的内容。我或多或少了解 super 函数的使用方式,但是 (1) 这样做有什么问题?:
class First(object):
def __init__(self):
print "first"
class Second(object):
def __init__(self):
print "second"
class Third(First, Second):
def __init__(self):
First.__init__(self)
Second.__init__(self)
print "that's it"
转到 super(),Andrew Kuchlings paper on Python Warts说:
usage of super() will also be correct when the Derived class inherits from multiple base classes and some or all of them have init methods
所以我把上面的例子改写如下:
class First(object):
def __init__(self):
print "first"
class Second(object):
def __init__(self):
print "second"
class Third(First, Second):
def __init__(self):
super(Third, self).__init__(self)
print "that's it"
然而,这只会运行它可以找到的第一个 init,它位于 First
中。 (2) super()
是否可以同时运行 First
和 Second
的 init,如果可以,如何? 运行 super(Third, self).__init__(self)
两次只运行 First.init() 两次..
增加一些困惑。如果继承类的 init() 函数采用不同的参数会怎样。例如,如果我有这样的事情:
class First(object):
def __init__(self, x):
print "first"
class Second(object):
def __init__(self, y, z):
print "second"
class Third(First, Second):
def __init__(self, x, y, z):
First.__init__(self, x)
Second.__init__(self, y, z)
print "that's it"
(3) 如何使用 super() 为不同的继承类初始化函数提供相关参数?
欢迎所有提示!
ps。由于我有几个问题,我将它们加粗并编号..
最佳答案
对于问题2,你需要在每个类中调用super:
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(First, Second):
def __init__(self):
super(Third, self).__init__()
print "that's it"
对于问题 3,这是无法做到的,您的方法需要具有相同的签名。但是你可以忽略父类中的一些参数或使用关键字参数。
关于python - 多重继承如何与 super() 和不同的 __init__() 参数一起工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16855087/