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

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

    class First(object):
      def __init__(self, a):
        print "first", a
        super(First, self).__init__(20)
    
    class Second(object):
      def __init__(self, a):
        print "second", a
        super(Second, self).__init__()
    
    class Third(First, Second):
      def __init__(self):
        super(Third, self).__init__(10)
        print "that's it"
    
    t = Third()
    

    Output is

    first 10
    second 20
    that's it
    

    Call to Third() locates the init defined in Third. And call to super in that routine invokes init defined in First. MRO=[First, Second]. Now call to super in init defined in First will continue searching MRO and find init defined in Second, and any call to super will hit the default object init. I hope this example clarifies the concept.

    If you don't call super from First. The chain stops and you will get the following output.

    first 10
    that's it
    

提交回复
热议问题