I have a base class and a few derived in Python:
class Base:
def Foo(self):
pass
# First derived class
class Der1(Base):
def OwnFoo(self):
# Do something 1
def OwnFoo2(self):
# Do something 2
def Foo(self):
# Do something 3
# Second derived class
class Der2(Base):
def OwnFoo(self):
# Do something 1
def OwnFoo2(self):
# Do something 2
def Foo(self):
# Do something 3
The question is:
I have some predefined code in Der1. Almost all functions from Der2 do the same. How can I write this with less code?
I can’t add that code to the parent. Parent class shouldn’t be touched.
For example, Der2.OwnFoo does the same as Der1.OwnFoo, maybe there is some construction in python just to call OwnFoo from first class and not to write that code again?
I can’t change the parent of Der1 and Der2! It should be Base.
Since you can’t change the inheritance structure, make a helper class that contains the common code and include it by composition rather than inheritance.
Of course, you could pass a reference to the parent instead of a string. I just did it this way for demonstration purposes.
Usage:
Output: