I have two parent classes I cannot redefine (say, A and B), with methods I need to overload using the exact same way (so as to obtain, say, BetterA and BetterB).
I could duplicate the code for both classes, but I am not satisfied with that.
In Python 3.6, I thought I can get rid of this using multi inheritance and a provider class.
This is what I obtained so far:
# here are the initial classes I cannot edit
class A:
def __init__(self, a=0):
self.a = a
class B:
def __init__(self, b=0):
self.b = b
# here is the provider class
class Provider:
def __init__(self, c, *args, **kwargs):
self.c = c
# more code here
self.init_child(*args, **kwargs)
# here are the new classes
class BetterA(Provider, A):
def init_child(self, *args, **kwargs):
A.__init__(*args, **kwargs)
class BetterB(Provider, B):
def init_child(self, *args, **kwargs):
B.__init__(*args, **kwargs)
if __name__ == '__main__':
a = BetterA(8, a=10)
b = BetterB(10, b=8)
This works, but it is not very graceful…
Especially, if I want to override more methods (always, in the same way), I have to recall them in BetterA and BetterB.
If there a better way to achieve what I want?