Jake Nguyen
Jake Nguyen

Reputation: 71

Inherit SOME but not all arguments from parent class's constructor? Python

Let's say I have parent class P

class P(object):
    def __init__(self, a, b, c):
        self._a = a
        self._b = b
        self._c = c

If a create another class C which is a child class of P, is it possible to inherit SOME parameters of P but not all (Let's say I just want parameters a,c from class P to be passed on to C). I know it's a weird question, and I don't know if there's an application to this, but I just can't seem to find an answer. Thank you in advance!

Upvotes: 1

Views: 2301

Answers (1)

MLavrentyev
MLavrentyev

Reputation: 1969

The only good way to do it as far as I know is to do something like the following:


class P:
    def __init__(self, a, b, c):
        self._a = a
        self._b = b
        self._c = c

class C(P):
    def __init__(self, a, b, c):
        super(C, self).__init__(a, b, c)
        self._b = b

Essentially, you call the superclass constructor to define all of the values, but then override the value (in this case, for self._b) later in the child class constructor.

Alternatively, if you don't want self._b to even be a thing in the class C, you can also do del self._b after the super().__init__() call to remove it altogether.

In general, though, it seems like bad practice to have a child class not have some of the fields that the parent class has, since other parts of the code may rely on that field being there.

Upvotes: 1

Related Questions