How does Python's super() work with multiple inheritance?

后端 未结 16 2154
孤街浪徒
孤街浪徒 2020-11-21 05:19

I\'m pretty much new in Python object oriented programming and I have trouble understanding the super() function (new style classes) especially when it comes to

16条回答
  •  温柔的废话
    2020-11-21 05:50

    Consider calling super().Foo() called from a sub-class. The Method Resolution Order (MRO) method is the order in which method calls are resolved.

    Case 1: Single Inheritance

    In this, super().Foo() will be searched up in the hierarchy and will consider the closest implementation, if found, else raise an Exception. The "is a" relationship will always be True in between any visited sub-class and its super class up in the hierarchy. But this story isn't the same always in Multiple Inheritance.

    Case 2: Multiple Inheritance

    Here, while searching for super().Foo() implementation, every visited class in the hierarchy may or may not have is a relation. Consider following examples:

    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
    

    Here, I is the lowest class in the hierarchy. Hierarchy diagram and MRO for I will be

    (Red numbers showing the MRO)

    MRO is I E C D A H F G B object

    Note that a class X will be visited only if all its sub-classes, which inherit from it, have been visited(i.e., you should never visit a class that has an arrow coming into it from a class below that you have not yet visited).

    Here, note that after visiting class C , D is visited although C and D DO NOT have is a relationship between them(but both have with A). This is where super() differs from single inheritance.

    Consider a slightly more complicated example:

    (Red numbers showing the MRO)

    MRO is I E C H D A F G B object

    In this case we proceed from I to E to C. The next step up would be A, but we have yet to visit D, a subclass of A. We cannot visit D, however, because we have yet to visit H, a subclass of D. The leaves H as the next class to visit. Remember, we attempt to go up in hierarchy, if possible, so we visit its leftmost superclass, D. After D we visit A, but we cannot go up to object because we have yet to visit F, G, and B. These classes, in order, round out the MRO for I.

    Note that no class can appear more than once in MRO.

    This is how super() looks up in the hierarchy of inheritance.

    Credits for resources: Richard L Halterman Fundamentals of Python Programming

提交回复
热议问题