super()如何处理多重继承?例如,给定:

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__()
        print "that's it"

Third的哪个父方法执行super()。__init__ refer to?我可以选择哪些运行吗?

我知道这与方法解析顺序(MRO)有关。


当前回答

考虑从子类调用super(). foo()。方法解析顺序(MRO)方法是解析方法调用的顺序。

案例1:单继承

在这种情况下,super(). foo()将在层次结构中向上搜索,并将考虑最接近的实现,如果找到,否则引发异常。在任何被访问的子类和它在层次结构上的超类之间,“is a”关系将始终为True。但是这个故事在多重继承中并不总是一样的。

案例2:多重继承

在这里,当搜索super(). foo()实现时,层次结构中每个被访问的类都可能是一个关系,也可能不是。考虑以下例子:

class A(object): pass
class B(object): pass
class C(A): pass
class D(A): pass
class E(C, D): pass
class F(B): pass
class G(B): pass
class H(F, G): pass
class I(E, H): pass

这里,I是层次结构中最低的类。层次图和MRO为我将

(红色数字为MRO)

MRO是I E C D A H F G B对象

注意,类X只有在继承自它的所有子类都被访问过的情况下才会被访问。例如,如果一个类下面有一个箭头,而你还没有访问过这个箭头,那么你永远不应该访问这个类)。

在这里,注意在访问类C之后,D被访问,尽管C和D DO NOT have是它们之间的关系(但它们都与a有关系)。这是super()不同于单一继承的地方。

考虑一个稍微复杂一点的例子:

(红色数字为MRO)

MRO是I E C H D A F G B对象

在这种情况下,我们从I到E再到c。下一步是A,但我们还没有访问A的子类D。然而,我们不能访问D,因为我们还没有访问D的子类H。剩下H作为下一个要访问的类。记住,如果可能的话,我们试图在层次结构中向上,所以我们访问它最左边的超类D。在D之后,我们访问A,但我们不能向上到object,因为我们还没有访问F、G和b。这些类,依次,为I完成MRO。

注意,任何类都不能在MRO中出现超过一次。

这就是super()在继承层次结构中的查找方式。

资源来源:Richard L Halterman Python编程基础

其他回答

我知道这并没有直接回答super()问题,但我觉得它有足够的相关性来分享。

还有一种方法可以直接调用每个继承的类:


class First(object):
    def __init__(self):
        print '1'

class Second(object):
    def __init__(self):
        print '2'

class Third(First, Second):
    def __init__(self):
        Second.__init__(self)

请注意,如果你这样做,你将不得不手动调用每个,因为我很确定First的__init__()不会被调用。

整体

假设所有东西都来自object(如果不是你自己的),Python会根据你的类继承树计算一个方法解析顺序(MRO)。MRO满足3个性质:

一个阶层的孩子比他们的父母更重要 左父母先于右父母 一个类在MRO中只出现一次

如果不存在这样的顺序,Python将出错。它的内部工作原理是类祖先的C3线性化。点击这里阅读:https://www.python.org/download/releases/2.3/mro/

当一个方法被调用时,该方法在MRO中第一次出现就是被调用的方法。任何没有实现该方法的类都将被跳过。在该方法中对super的任何调用都将调用MRO中该方法的下一次出现。因此,在继承中放置类的顺序以及在方法中放置super调用的位置都很重要。

注意,你可以通过使用__mro__方法在python中看到MRO。

例子

下面所有的例子都有菱形类继承,如下所示:

    Parent
    /   \
   /     \
Left    Right
   \     /
    \   /
    Child

MRO是:

孩子 左 正确的 父

您可以通过调用Child来测试这一点。__mro__,返回:

(__main__.Child, __main__.Left, __main__.Right, __main__.Parent, object)

每一种方法都以超第一

class Parent(object):
    def __init__(self):
        super(Parent, self).__init__()
        print("parent")

class Left(Parent):
    def __init__(self):
        super(Left, self).__init__()
        print("left")

class Right(Parent):
    def __init__(self):
        super(Right, self).__init__()
        print("right")

class Child(Left, Right):
    def __init__(self):
        super(Child, self).__init__()
        print("child")

孩子()输出:

parent
right
left
child
    

在每个方法中都有超级最后

class Parent(object):
    def __init__(self):
        print("parent")
        super(Parent, self).__init__()

class Left(Parent):
    def __init__(self):
        print("left")
        super(Left, self).__init__()

class Right(Parent):
    def __init__(self):
        print("right")
        super(Right, self).__init__()

class Child(Left, Right):
    def __init__(self):
        print("child")
        super(Child, self).__init__()

孩子()输出:

child
left
right
parent

当不是所有类都调用super时

如果不是继承链中的所有类都调用super,那么继承顺序最重要。例如,如果Left不调用super,那么Right和Parent上的方法永远不会被调用:

class Parent(object):
    def __init__(self):
        print("parent")
        super(Parent, self).__init__()

class Left(Parent):
    def __init__(self):
        print("left")

class Right(Parent):
    def __init__(self):
        print("right")
        super(Right, self).__init__()

class Child(Left, Right):
    def __init__(self):
        print("child")
        super(Child, self).__init__()

孩子()输出:

child
left

或者,如果Right没有调用super, Parent仍然被跳过:

class Parent(object):
    def __init__(self):
        print("parent")
        super(Parent, self).__init__()

class Left(Parent):
    def __init__(self):
        print("left")
        super(Left, self).__init__()

class Right(Parent):
    def __init__(self):
        print("right")

class Child(Left, Right):
    def __init__(self):
        print("child")
        super(Child, self).__init__()

在这里,Child()输出:

child
left
right

调用特定父节点上的方法

如果你想访问一个特定父类的方法,你应该直接引用这个类,而不是使用super。Super是关于遵循继承链,而不是到达特定类的方法。

下面是如何引用一个特定的父方法:

class Parent(object):
    def __init__(self):
        super(Parent, self).__init__()
        print("parent")

class Left(Parent):
    def __init__(self):
        super(Left, self).__init__()
        print("left")

class Right(Parent):
    def __init__(self):
        super(Right, self).__init__()
        print("right")

class Child(Left, Right):
    def __init__(self):
        Parent.__init__(self)
        print("child")

在这种情况下,Child()输出:

parent
child

把这个答案贴出来供我将来参考。

Python多重继承应该使用菱形模型,并且函数签名不应该在模型中更改。

    A
   / \
  B   C
   \ /
    D

示例代码片段为;-

class A:
    def __init__(self, name=None):
        #  this is the head of the diamond, no need to call super() here
        self.name = name

class B(A):
    def __init__(self, param1='hello', **kwargs):
        super().__init__(**kwargs)
        self.param1 = param1

class C(A):
    def __init__(self, param2='bye', **kwargs):
        super().__init__(**kwargs)
        self.param2 = param2

class D(B, C):
    def __init__(self, works='fine', **kwargs):
        super().__init__(**kwargs)
        print(f"{works=}, {self.param1=}, {self.param2=}, {self.name=}")

d = D(name='Testing')

这里类A是对象

在这种情况下,你试图继承的每个类都有自己的init位置参数,只需调用每个类自己的init方法,如果试图继承多个对象,则不要使用super。

class A():
    def __init__(self, x):
        self.x = x

class B():
    def __init__(self, y, z):
        self.y = y
        self.z = z

class C(A, B):
    def __init__(self, x, y, z):
        A.__init__(self, x)
        B.__init__(self, y, z)

>>> c = C(1,2,3)
>>>c.x, c.y, c.z 
(1, 2, 3)

在python 3.5+中,继承看起来是可预测的,对我来说非常好。 请看下面的代码:

class Base(object):
  def foo(self):
    print("    Base(): entering")
    print("    Base(): exiting")


class First(Base):
  def foo(self):
    print("   First(): entering Will call Second now")
    super().foo()
    print("   First(): exiting")


class Second(Base):
  def foo(self):
    print("  Second(): entering")
    super().foo()
    print("  Second(): exiting")


class Third(First, Second):
  def foo(self):
    print(" Third(): entering")
    super().foo()
    print(" Third(): exiting")


class Fourth(Third):
  def foo(self):
    print("Fourth(): entering")
    super().foo()
    print("Fourth(): exiting")

Fourth().foo()
print(Fourth.__mro__)

输出:

Fourth(): entering
 Third(): entering
   First(): entering Will call Second now
  Second(): entering
    Base(): entering
    Base(): exiting
  Second(): exiting
   First(): exiting
 Third(): exiting
Fourth(): exiting
(<class '__main__.Fourth'>, <class '__main__.Third'>, <class '__main__.First'>, <class '__main__.Second'>, <class '__main__.Base'>, <class 'object'>)

正如你所看到的,它对每个继承链调用foo一次,其顺序与继承链的顺序相同。你可以通过调用.mro来获得订单:

Fourth -> Third -> First -> Second -> Base ->对象