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

后端 未结 16 2220
孤街浪徒
孤街浪徒 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条回答
  •  Happy的楠姐
    2020-11-21 05:35

    Overall

    Assuming everything descends from object (you are on your own if it doesn't), Python computes a method resolution order (MRO) based on your class inheritance tree. The MRO satisfies 3 properties:

    • Children of a class come before their parents
    • Left parents come before right parents
    • A class only appears once in the MRO

    If no such ordering exists, Python errors. The inner workings of this is a C3 Linerization of the classes ancestry. Read all about it here: https://www.python.org/download/releases/2.3/mro/

    Thus, in both of the examples below, it is:

    1. Child
    2. Left
    3. Right
    4. Parent

    When a method is called, the first occurrence of that method in the MRO is the one that is called. Any class that doesn't implement that method is skipped. Any call to super within that method will call the next occurrence of that method in the MRO. Consequently, it matters both what order you place classes in inheritance, and where you put the calls to super in the methods.

    With super first in each method

    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"
    

    Child() Outputs:

    parent
    right
    left
    child
    

    With super last in each method

    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() Outputs:

    child
    left
    right
    parent
    

提交回复
热议问题