I have a situation where a base class method (the __init__
method in Python) does a lot of work. The derived classes override __init__
to simply set an object variable and then delegate to the base class __init__
. This works fine but now I have a situation.
I have some code that fits perfectly in the base class __init__
which all the other derived classes except one (call it A
) need to use. Imagine if the base class __init__
was something like this.
def __init__(self):
Action 1...
Action 2...
Now, all the derived classes simply delegate directly to this one. However, A
should have only Action 2 in its __init__
. Now the sitation is ugly. I can split Action 1 and Action 2 into two separate functions and have the base class simply call Action2
. Then most classes will have their init something like this.
def __init__(self):
self.Action1()
Other init code...
super().__init__()
and for class A
, it will be
def __init__(self):
Some init code....
super().__init__()
But you can see that there's a piece of code (the call to self.Action1
that) I have to repeat in most of the derived classes. This is bad. I'm not sure how to code this up elegantly with minimum repeated code and need some advice on how to do it.