MyNick
MyNick

Reputation: 566

Python inheritance - add argument to parent method

I have a base class with function run. For example:

class A:
    @abstractmethod
    def run(self, steps):
        ...

It is possible to define class B with more arguments to the run method.

class B(A):
    def run(self, steps, save):
        ...

Working with typing, I can specify if a function gets either A or B as argument. By specifying the function gets A, I tell that I only need the basic interface of run. While specifying B says I need the extended one.

The purpose of this design is to declare a base interface that all the children share but each one can have an extended API.

This is impossible to be done in other languages. Hence I wonder, is it an anti-pattern? Is it something legit to do?

Upvotes: 1

Views: 879

Answers (1)

Mike L
Mike L

Reputation: 327

In Python you can do something like the following.

class A:

  def run(self, steps):
    print("Using class A's run.")
    print(f"steps are {steps}")


class B(A):

  def run(self, steps, other_arg=None):
    if other_arg:
      print("Using class B's override.")
      print(f"steps are {steps}")
    else:
      # Use parent's run logic instead.
      super().run(steps)

x = B()
x.run(100)
x.run(30, other_arg="something")

# Using class A's run.
# steps are 100
# Using class B's override.
# steps are 30

Now, should you do this? There is a time and a place. You can get into trouble as well. Imagine you break the interface of the core object you're inheriting from, so the core object loses its abstraction value. You'd have been better off having two objects or rewriting your abstraction to be more robust to the differences in object you wish you represent.

Edit: Note that the original question changed to make the base run method abstract. The solution posted here is mostly invalidated by that.

Upvotes: 1

Related Questions