Raven
Raven

Reputation: 741

What is a correct way to override child __init__ function?

Given a child-parent structure like so:

class Parent:
    def __init__(self, param1=1, param2=2, param3=3, param4=4):
        """
        Parent docstring here
        :param param1: param1 stuff
        :param param2: param2 stuff
        :param param3: param3 stuff
        :param param4: param4 stuff
        """
        self.param1 = param1
        self.param2 = param2
        self.param3 = param3
        self.param4 = param4


class Child(Parent):
    def __init__(self, param1=1, param2=2, param3=3, param4=4,
                 child_param1='a', child_param2='b', child_param3='c'):
        """
        Child implementation of parent.
        :param param1: do I need this again???
        :param param2: do I need this again???
        :param param3: do I need this again???
        :param param4: do I need this again???
        :param child_param1: child parameter 1
        :param child_param2: child parameter 2
        :param child_param3: child parameter 3
        """
        super().__init__(param1, param2, param3, param4)
        self.child_param3 = child_param3
        self.child_param1 = child_param1
        self.child_param2 = child_param2

What is the correct way of implementing a child without repeating both the docstring of the parent and each individual parameter? I want the parameter description to be inherited from the parent. I also don't want to re-specify the default values every time I inherit from the parent. I could do this, but this doesn't seem like the right way:

class Child(Parent):
    def __init__(self, child_param1='a', child_param2='b', child_param3='c', **parent_args):
        super(**parent_args)
        # rest of the code goes here...

Upvotes: 0

Views: 67

Answers (1)

Tom Dalton
Tom Dalton

Reputation: 6190

You can't inherit default values from the parent, but you can have a 'special (unique)' default value and then use that to set the "real" default. E.g.

DEFAULT = object()


class Vehicle:
    DEFAULT_WHEELS = 4

    def __init__(self, wheels=DEFAULT):
        if wheels is DEFAULT:
            wheels = self.DEFAULT_WHEELS
        self.wheels = wheels


class Car(Vehicle):
    DEFAULT_COLOUR = "Red"

    def __init__(self, colour=DEFAULT, **kwargs):
        super().__init__(**kwargs)

        if colour is DEFAULT:
            colour = self.DEFAULT_COLOUR
        self.colour = colour


# You can also use the class-level default to modify the
# defaults without having to re-write the init:

class Tricycle(Vehicle):
    DEFAULT_WHEELS = 3

Upvotes: 1

Related Questions