I am trying to design a class structure that allows the user to define their own class that overloads predefined methods in other classes. In this case the user would create the C class to overload the "function" method in D. The user created C class has common logic for other user created classes A and B so they inherit from C to overload "function" but also inherit from D to use D's other methods. The issue I am having is how to pass "value" from A and B to D and ignore passing it to C. What I currently have written will produce an error as C does not have "value" as an argument.
I know that I can add "value" (or *args) to C's init method and the super call but I don't want to have to know what inputs other classes need in order to add new classes to A and B. Also, if I swap the order of C and D I won't get an error but then I don't use C's overloaded "function". Is there an obvious way around this?
class D(SomethingElse):
def __init__(self, value, **kwargs):
super(D, self).__init__(**kwargs)
self.value = value
def function(self):
return self.value
def other_method(self):
pass
class C(object):
def __init__(self):
super(C, self).__init__()
def function(self):
return self.value*2
class B(C, D):
def __init__(self, value, **kwargs):
super(B, self).__init__(value, **kwargs)
class A(C, D):
def __init__(self, value, **kwargs):
super(A, self).__init__(value, **kwargs)
a = A(3)
print(a.function())
>>> 6
class Aon linesuper(A, self).__init__(value, **kwargs),__init__() takes 1 positional argument but 2 were givenbecausesuper(A, self)tries to referclass Cand its__init__doesn't recieve any positional arguments. I had to add*args, **kwargsto mehtioned__init__and writesuper(C, self).__init__(*args, **kwargs)and everything worked. It was python3.6.super(YourClass, self)you refer to the next class in MRO. You can writeprint(A.__mro__)youll get[A, C, D, SomethingElse, object]. So that,class Cshould be aware of argumentsclass Dshould recieve. The most convenient way is using*args, **kwargs. Read, please, this realpython.com/lessons/multiple-inheritance-python, may contain more details.