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

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

    In python 3.5+ inheritance looks predictable and very nice for me. Please looks at this code:

    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__)
    

    Outputs:

    Fourth(): entering
     Third(): entering
       First(): entering Will call Second now
      Second(): entering
        Base(): entering
        Base(): exiting
      Second(): exiting
       First(): exiting
     Third(): exiting
    Fourth(): exiting
    (, , , , , )
    

    As you can see, it calls foo exactly ONE time for each inherited chain in the same order as it was inherited. You can get that order by calling .mro :

    Fourth -> Third -> First -> Second -> Base -> object

提交回复
热议问题