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

Gio*_*iuc 5 python oop inheritance super python-3.x

假设我有一些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()
Run Code Online (Sandbox Code Playgroud)

此脚本打印"女儿".反正是否确保调用基类的所有__init__方法?我想出的一个方法是:

class Daughter(Mother, Father):
    def __init__(self):
        print("Daughter")
        for base in type(self).__bases__:
            base.__init__(self)
Run Code Online (Sandbox Code Playgroud)

这个脚本打印"女儿","母亲","父亲".使用super()或其他方法有一个很好的方法吗?

Rya*_*ing 5

Raymond Hettinger在PyCon 2015的Super Considered Super演讲中解释得非常好.简短的回答是肯定的,如果你这样设计,并super().__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")
Run Code Online (Sandbox Code Playgroud)

这个名字super很不幸,它确实通过基类运行.