In a python program, I implemented some class A
, and a subclass B
which extends some of A
's methods and implements new ones. So it's something that looks like this.
class A:
def method(self):
print("This is A's method.")
class B(A):
def method(self):
super().method()
print("This is B's method.")
def another_method(self):
pass
Later, I wanted to use an object which would have access to all of B
's methods, except for a small change in method
: this object would have to first call A.method
, and then do other things, different from what I added in B.method
. I thought it was natural to introduce a class C
which would inherit from B
but modify method
, so I defined C
like this.
class C(B):
def method(self):
super(B, self).method()
print("This is C's method.")
Everything seems to work as I expect. However, I stumbled across this question and this one, which both address similar problems as what I described here. In both posts, someone quickly added a comment to say that calling a grandparent method in a child when the parent has overridden this method is a sign that there is something wrong with the inheritance design.
How should I have coded this? What would be a better design? Of course this is a toy example and I guess the answer might depend on the actual classes I defined. To give a more complete picture, let's say the method method
from the example represents a single method in my actual program, but the method another_method
represents many different methods.