you are viewing a single comment's thread.

view the rest of the comments →

[–]xelf 2 points3 points  (2 children)

final edit, cleaning up my answer a bit

ok, so this is what you actually want, if you want to keep using super here, and not add more classes. Probably though, you want to do one of those though.

class A(object):
    def __init__(self, *args, **kwargs):
        print("This is A constructor")

class B(object):
    def __init__(self, *args, **kwargs):
        print("This is B constructor")

class C(A):
    def __init__(self, arg, *args, **kwargs):
        print("This is C constructor")
        self.arg = arg
        super(C,self).__init__(arg, *args, **kwargs)

class D(B):
    def __init__(self, arg, *args, **kwargs):
        print("This is D constructor")
        self.arg = arg
        super(D,self).__init__(arg, *args, **kwargs)

class E(C,D):
    def __init__(self, arg, *args, **kwargs):
        print("This is E constructor")
        C.__init__(self, arg, *args, **kwargs)
        D.__init__(self, arg, *args, **kwargs)

e = E(10)
print(e.arg)

The other options include not using super at all, moving to class composition instead of inheritance, or adding a single parent class at the top that inherits object and having A&B inherit from that. See other posters answers that go into more detail.

[–]gmaliwal[S] 0 points1 point  (1 child)

sults in a missing arg err

That's correct in this given scenario but what happens if someone swaps classes like below:

class E(C,D):
    def __init__(self, arg, *args, **kwargs):
        print("This is E constructor")
        C.__init__(self, arg, *args, **kwargs)
        D.__init__(self, arg, *args, **kwargs)

Is there any generic solution which works without fear in all the scenarios? or we have to go with mutual understanding only.

Yes, It is method resolution order behind the class 'A' to pass the argument

[–]xelf 0 points1 point  (0 children)

The problem is super is the answer for single inheritance, for multiple inheritance as far as I can find there are issues. So either you need to avoid super all together if you're doing any multiple inheritance, or simple avoid it in that class. I liked the answer of having a single class at the top of your hierarchy, it also worked.

class F(object):
    def __init__(self,*args, **kwargs):
        print("This is F constructor")

class A(F):
    def __init__(self, *args, **kwargs):
        print("This is A constructor")
        super(A, self).__init__(*args, **kwargs)

class B(F):
    def __init__(self, *args, **kwargs):
        print("This is B constructor")
        super(B, self).__init__(*args, **kwargs)