python - 多重继承如何与 super() 和不同的 __init__() 参数一起工作?

标签 python class constructor multiple-inheritance super

我只是在深入研究一些更高级的 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() 是否可以同时运行 FirstSecond 的 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/

相关文章:

python - BuildError : Could not build url for endpoint 'user' with values ['nickname' ]. 您是否忘记指定值 ['page' 、 'username' ]?

python - systemd 服务无法启动 bash 脚本

python - amazon ec2 centOS 上没有名为 tkinter 的模块

python - 如何在 Python 中获取类的文件路径?

c++ - 初始化构造函数 C++

python - 尝试使用 "pyinstaller <scriptname.py>"并得到 "TypeError: an integer is required (got type bytes)"

PHP:mysql 语句有问题。

python - 'class' 任务需要指导(初学者)

c# - 为什么 c# 编译器在使用具有 new() 约束的泛型类型调用 new 时发出 Activator.CreateInstance?

constructor - F# 使用构造函数作为函数