views:

29

answers:

1

I have an base class, and two subclasses. Each needs to implement a method that's defined in the base class (but in the base class raises an NotImplementedError.. the base class is basically an abstract class).

But, the implementation of the method in one of the subclasses requires more parameters than in the other subclass.

class SubclassA(AbstractBase):
    def method(arg1, arg2):
        # Do stuff using arg1 and arg2

class SubclassB(AbstractBase):
    def method(arg1, arg2, arg3):
        # Do stuff using arg1, arg2, and arg3

This makes calling code look something like this:

if condition:
    obj = SubClassA()
else:
    obj = SubClassB()

# A bunch more code that preps arg1, arg2, arg3

if condition:
    obj.method(arg1, arg2)
else:
    obj.method(arg1, arg2, arg3)

I could add *args and **kwargs to the shorter parameter list (which would just go ignored) so that the calling code can call either subclass's function with the same parameter set. That would remove the second conditional in the calling code.

Am I missing some feature of python, or thinking about this in the wrong way? What other options are there for making this cleaner?

+2  A: 

If the meaning of arg1 and arg2 is the same, you can just add an ignored parameter:

  class SubclassA(AbstractBase):
     def method(arg1, arg2, argIgnored):
        # Do stuff using arg1 and arg2

and if possible remove the 2-arg method from the base class. It would be better to only have a 3-arg method in the base class with the third argument a keyword like:

# in base class only this
def method(arg1, arg2, arg3=None)

This may of course not be feasible it the base class is in use at other places, or is not your base class.

extraneon