Reputation: 1329
I have a class which subclass another. I would like to skip a part of the initialization process, for example:
class Parent:
__init__(self, a, b, c, ...):
# part I want to keep:
self.a = a
self.b = b
self.c = c
...
# part I want to skip, which is memory and time consuming
# but unnecessary for the subclass:
self.Q = AnotherClass()
class Child(Parent):
__init__(self):
#a part of the parent initialization process, then other stuff
The two solutions I've come up with are:
Parent
class which wouldn't include the unwanted part of the initialization for the Child
, orWhich is best, or are there better methods?
Upvotes: 2
Views: 2207
Reputation: 23233
What about wrapping creation of Q
into private method, and overriding that method in subclass?
class Parent:
def __init__(self, a, b, c, ...):
# part I want to keep:
self.a = a
self.b = b
self.c = c
self._init_q()
def _init_q():
self.Q = AnotherClass()
class Child(Parent):
def _init_q(self):
pass # do not init q when creating subclass
It's not a cleanest approach, since if Child
does not need Q
either it shouldn't be a child of Parent, or maybe AnotherClass
is misplaced (maybe it should be injected to methods which needs it) but it solves your issue without changing any of class interfaces.
Upvotes: 7