Search code examples
pythonpython-3.xclasscode-duplication

Is it possible to avoid rewriting all of a superclasses constructor parameters in a subclass?


Say for example I have an abstract class Animal with multiple parameters arguments, and I want to create a subclass Dog with all of Animal's properties, but with the additional property of race. As far as I know the only way of doing this:

from abc import ABC

class Animal(ABC):
    def __init__(self, name, id, weight):
        self.name = name
        self.id = id
        self.weight = weight

class Dog(Animal):
    def __init__(self, name, id, weight, race) # Only difference is race
        self.race = race
        super().__init__(name, id, weight)

Is there a way of doing this that doesn't include duplicating all of Animal's constructor parameters within Dog's constructor? This can get quite tedious when there are a lot of parameters, as well as making the code look repetitive.


Solution

  • You could use catch-all arguments, *args and **kwargs, and pass those on to the parent:

    class Dog(Animal):
        def __init__(self, race, *args, **kwargs):
            self.race = race
            super().__init__(*args, **kwargs)
    

    This does require that you put additional positional arguments at the front:

    Dog('mongrel', 'Fido', 42, 81)
    

    You can still name each argument explicitly when calling, at which point order no longer matters:

    Dog(name='Fido', id=42, weight=81, race='mongrel')