I have a Base
class with certain method and w/o any parameters:
class Base():
def pretty_method(self):
print('Hi!')
And there are several subclasses and they need additional proceeding in pretty_method
with new parameter x
.
class A(Base):
def pretty_method(self, x):
super().pretty_method()
print('X in A is {}'.format(x))
class B(Base):
def pretty_method(self, x):
super().pretty_method()
print('X in B is {}'.format(x))
So in that case I have inconsistency in class methods signature.
In other hand I could deal with unused x
parameter in base class:
class Base():
def pretty_method(self, x=None):
print('Hi!')
That is kinda useless, but keeps signatures in consistency. What is more preferable approach?
Adding new attributes / methods in a derived class is fine, removing them isn't because it violates the Liskov substitution principle.
Consider: all classes in (modern) Python derive from object
, and they'd be useless if they didn't add new attributes &/or methods. So it's perfectly normal to add new args to a derived class's __init__
method.
Of course, if you expect the majority of the derived classes to use the x
argument, then it's perfectly fine to add it to the base class too, even though the base class itself doesn't use it.
On a related note, it's a common practice to add methods to a base class that the base class itself doesn't use but which the derived classes are expected to override. In such cases, it's normal for the base method to raise NotImplemented
. You don't need to supply such methods in the base class, but it does make the error message more informative in case someone forgets to supply the method in their derived class.