I have 2 classes each implementing a specific behavior and using parent classes.
Now I have a new class that needs to use either behavior but which one can only be determined during/after construction.
That is currently being done by using multiple inheritance.
However as the base classes were not written taking this into account the contained super() call will call into the wrong sub-tree
Consider the following MWE:
class A:
def __init__(self, use_b):
self.init_b = use_b # Maybe complicated
def foo(self):
print("A")
class B(A):
def foo(self):
super().foo()
print("B")
class C1(A):
def foo(self):
super().foo()
print("C1")
class C2(C1):
def foo(self):
super().foo()
print("C2")
class D(B, C2):
def __init__(self, *args):
super().__init__(*args)
self.use_b = self.init_b
def foo(self):
if self.use_b:
B.foo(self)
else:
C2.foo(self)
d = D(True)
d.foo() # Expected: "A B"
print("NEXT")
d = D(False)
d.foo() # Expected: "A C1 C2"
Somewhere in A a property is initialized that is used in D to determine the appropriate class to use. Both of the candidates B and C2 inherit from the base class as they are/used to be independent implementations
It works for calling C2.foo but calling B.foo ends up calling foo in C2 and C1 too, which I do not want.
I do know WHY this happens (MRO) but have no good idea to resolve this.
I might be able to have D only inherit from A, initialize this and then decide which subclass to use, i.e.:
class D(A):
def __init__(self, *args):
super().__init__(*args)
if self.init_b:
self.impl = B(*args)
else:
self.impl = C2(*args)
def foo(self):
self.impl.foo()
But this has 3 issues:
- It initializes at least
Amultiple times. That is bad for performance and might fail ifA.__init__modifies the ref-type args (e.g. lists) - It might fail if there are some args only
BandC2understand soAcan't handle them - I'll need to implement and wrap all methods of
Athat could be called. If I forget one that was overwritten by either of theBorCclasses the behavior will be silently wrong. Similar for properties
Is there a clean and safe way to handle this scenario?
Dwill know this