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

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

    This is to how I solved to issue of having multiple inheritance with different variables for initialization and having multiple MixIns with the same function call. I had to explicitly add variables to passed **kwargs and add a MixIn interface to be an endpoint for super calls.

    Here A is an extendable base class and B and C are MixIn classes both who provide function f. A and B both expect parameter v in their __init__ and C expects w. The function f takes one parameter y. Q inherits from all three classes. MixInF is the mixin interface for B and C.

    • IPython NoteBook Of This Code
    • Github Repo with code example
    
    class A(object):
        def __init__(self, v, *args, **kwargs):
            print "A:init:v[{0}]".format(v)
            kwargs['v']=v
            super(A, self).__init__(*args, **kwargs)
            self.v = v
    
    
    class MixInF(object):
        def __init__(self, *args, **kwargs):
            print "IObject:init"
        def f(self, y):
            print "IObject:y[{0}]".format(y)
    
    
    class B(MixInF):
        def __init__(self, v, *args, **kwargs):
            print "B:init:v[{0}]".format(v)
            kwargs['v']=v
            super(B, self).__init__(*args, **kwargs)
            self.v = v
        def f(self, y):
            print "B:f:v[{0}]:y[{1}]".format(self.v, y)
            super(B, self).f(y)
    
    
    class C(MixInF):
        def __init__(self, w, *args, **kwargs):
            print "C:init:w[{0}]".format(w)
            kwargs['w']=w
            super(C, self).__init__(*args, **kwargs)
            self.w = w
        def f(self, y):
            print "C:f:w[{0}]:y[{1}]".format(self.w, y)
            super(C, self).f(y)
    
    
    class Q(C,B,A):
        def __init__(self, v, w):
            super(Q, self).__init__(v=v, w=w)
        def f(self, y):
            print "Q:f:y[{0}]".format(y)
            super(Q, self).f(y)
    

提交回复
热议问题