有没有办法用super()调用Python中每个基class的__init__方法?

Is there a way to use super() to call the __init__ method of each base class in Python?

假设我有一些 Python 代码:

class Mother:
    def __init__(self):
        print("Mother")

class Father:
    def __init__(self):
        print("Father")

class Daughter(Mother, Father):
    def __init__(self):
        print("Daughter")
        super().__init__()

d = Daughter()

此脚本打印 "Daughter"。有什么方法可以确保调用基 类 的所有 __init__ 方法吗?我想出的一种方法是:

class Daughter(Mother, Father):
    def __init__(self):
        print("Daughter")
        for base in type(self).__bases__:
            base.__init__(self)

此脚本打印 "Daughter"、"Mother"、"Father"。有使用 super() 或其他方法的好方法吗?

Raymond Hettinger 在 PyCon 2015 的演讲 Super Considered Super 中很好地解释了这一点。简短的回答是肯定的,如果你这样设计,并在每个 classsuper().__init__()

class Mother:
    def __init__(self):
        super().__init__()
        print("Mother")

class Father:
    def __init__(self):
        super().__init__()
        print("Father")

class Daughter(Mother, Father):
    def __init__(self):
        super().__init__()
        print("Daughter")

这个名字 super 很不幸,它确实在基础 classes 中起作用。