I am having a parent class A with few classes inheriting from it (B,C,...).
I have some function is_class_A that is implemented in A, and I want to override it in B and C in the same way.
Let say:
class A:
def is_class_A():
print("We are in class A")
class B(A):
def is_class_A():
print("Nope")
class C(A):
def is_class_A():
print("Nope")
Take in mind both functions that implement in class A and in the others, are long, and more complicate.
2 solutions I came in my mind to avoid the duplication in B, C implementation:
Using in class C:
def is_class_A():
return B.is_class_A()
I am not sure how this will be functional, because an object of C is not an object of B. And I don't pass here any self, so I don't see how this will work, maybe something similar can?
Next solution is using another heritage:
class C(B)
This won't work always, since not always possible (if they have different attributes) and might not fit the design purpose.
My best attempt so far is to use another class:
class BC(A):
def is_class_A():
print("Nope")
class B(BC):
pass
class C(BC):
pass
What do you think? Some more ideas? Maybe something more technical that won't involve with the program design?
Thanks.
BCis not a bad idea as long as your class hierarchy does not get too deep. As long as you do not introduce one hierarchy level for each common functionality, it should be fine. You also may also look at multiple inheritance in Python.B,Cinherent in it, and implement it there? but in my function I may use many attributes thatAhave.. sounds like getting complicatedisClassAoverride in a separate classZ, then useclass B(Z, A): .... Note thatZhas to come first to ensure thatZ.isClassAis used in preference toA.isClassA. I'm not sure if I actually like this idea, though; mix-ins usually add new functionality rather than overriding existing functionality. I think I would go with the intermediateBCclass as well. I don't know that you can really make the proper design decision based on this example, though: it's too abstract.