1

I have a parent class with an unused argument in private function _f(i)

class Parent:
    def _f(i):
        return range(m)

    def g():
        for i in range(n)
            for j in _f(i)
                # do something

which is intended to be used in overriden method in subclasses

class Child:
    def _f(i):
        return range(i, m)

Having an unused argument feels ugly, but it saves me from code duplication in method g(). Is there any suggested way to avoid it, or should I leave it as it is?

Chetan Kinger
  • 15,069
  • 6
  • 45
  • 82
blue_note
  • 27,712
  • 9
  • 72
  • 90

2 Answers2

1

It looks like the objective is to reuse the code in the g function such that the range of the second for loop can be changed through class extension. A better solution would be to get rid of the i parameter from the f function altogether and use instance variables instead.

Parent class

class Parent:
    def _f():
        return range(m)

    def g():
        for i in range(n)
            for j in _f()
                # do something

Child class

class Child:
    def __init__(self, i):
         self.i = i

    def _f():
        return range(self.i, m)

An immediate advantage of this approach would be that the contract for the f function doesn't need to be changed if one chooses to add more inputs that need to be used within the function in the future.

Note : This question has been marked as language agnostic. Any syntactical errors in the above code are intentional.

Chetan Kinger
  • 15,069
  • 6
  • 45
  • 82
0

In some OOP oriented languages like Java or C# there are abstract methods that would delegate the implementation to the child class, however in python the only way to use them is with the abc package, the other way to do it would be with interfaces.

Relevant question Abstract methods in Python

J. Pichardo
  • 3,077
  • 21
  • 37