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