Calling methods in superclass constructor or subclass constructor?

1. Passing a configuration to a method __init__

that calls register

implicitly:

class Base:

    def __init__(self, *verbs):
        if not verbs:
          verbs = "get", "post"
        self._register(verbs)

    def _register(self, *verbs):
        pass


class Sub(Base):

    def __init__(self):
        super().__init__("get", "post", "put")

      

2. Call register

explicitly in a subclass method __init__

:

class Base:

    def __init__(self):
        self._register("get", "post")

    def _register(self, *verbs):
        pass


class Sub(Base):

    def __init__(self):
        self._register("get", "post", "put")

      

I am using Python 3.

Which is better or more pythonic? Or is it just a matter of taste?

+2


a source to share


4 answers


I think none of these options are good. The closest solution would probably be the following:

class Base(object):

    def __init__(self):
        self._register("get", "post")


class Sub(Base):

    def __init__(self):
        super(Sub, self).__init__()
        self._register("put")

      



I'm also wondering if it wouldn't be better to register verbs at the class level. They are probably identical for all instances, so why are they registered for each instance separately?

+3




If anything that extends the base class behaves like this, I'll personally call from the base class constructor. If not and the behavior changes, I would call from the subclass ...

As for the more Pythonic - don't subscribe to the cult - write code that works ...



Martin

0


a source


IMHO, the second way is better. The "more pythonic" way is to make things as explicit as practical. You won't need to keep track of the parent class's constructor to see what it does with those arguments ...

0


a source


I would definitely use the first form. The question I asked myself is, "What if the initialization of the base class is changed one day? Do I want subclasses to benefit from the update or not?" In almost all of my code, the answer is yes ... :)

0


a source







All Articles