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

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

    Posting this answer for my future referance.

    Python Multiple Inheritance should use a diamond model and the function signature shouldn't change in the model.

        A
       / \
      B   C
       \ /
        D
    

    The sample code snippet would be ;-

    class A:
        def __init__(self, name=None):
            #  this is the head of the diamond, no need to call super() here
            self.name = name
    
    class B(A):
        def __init__(self, param1='hello', **kwargs):
            super().__init__(**kwargs)
            self.param1 = param1
    
    class C(A):
        def __init__(self, param2='bye', **kwargs):
            super().__init__(**kwargs)
            self.param2 = param2
    
    class D(B, C):
        def __init__(self, works='fine', **kwargs):
            super().__init__(**kwargs)
            print(f"{works=}, {self.param1=}, {self.param2=}, {self.name=}")
    
    d = D(name='Testing')
    

    Here class A is object

提交回复
热议问题