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

后端 未结 16 2165
孤街浪徒
孤街浪徒 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:39

    Your code, and the other answers, are all buggy. They are missing the super() calls in the first two classes that are required for co-operative subclassing to work.

    Here is a fixed version of the code:

    class First(object):
        def __init__(self):
            super(First, self).__init__()
            print("first")
    
    class Second(object):
        def __init__(self):
            super(Second, self).__init__()
            print("second")
    
    class Third(First, Second):
        def __init__(self):
            super(Third, self).__init__()
            print("third")
    

    The super() call finds the next method in the MRO at each step, which is why First and Second have to have it too, otherwise execution stops at the end of Second.__init__().

    This is what I get:

    >>> Third()
    second
    first
    third
    

提交回复
热议问题