Class hierarchies and constructors are related. Parameters from a child class need to be passed to their parent.
So, in Python, we end up with something like this:
class Parent(object):
def __init__(self, a, b, c, ka=None, kb=None, kc=None):
# do something with a, b, c, ka, kb, kc
class Child(Parent):
def __init__(self, a, b, c, d, e, f, ka=None, kb=None, kc=None, kd=None, ke=None, kf=None):
super(Child, self).__init__(a, b, c, ka=ka, kb=kb, kc=kc)
# do something with d, e, f, kd, ke, kf
Imagine this with a dozen child classes and lots of parameters. Adding new parameters becomes very tedious.
Of course one can dispense with named parameters completely and use *args and **kwargs, but that makes the method declarations ambiguous.
Is there a pattern for elegantly dealing with this in Python (2.6)?
By "elegantly" I mean I would like to reduce the number of times the parameters appear. a, b, c, ka, kb, kc all appear 3 times: in the Child constructor, in the super() call to Parent, and in the Parent constructor.
Ideally, I'd like to specify the parameters for Parent's init once, and in Child's init only specify the additional parameters.
I'd like to do something like this:
class Parent(object):
def __init__(self, a, b, c, ka=None, kb=None, kc=None):
print 'Parent: ', a, b, c, ka, kb, kc
class Child(Parent):
def __init__(self, d, e, f, kd='d', ke='e', kf='f', *args, **kwargs):
super(Child, self).__init__(*args, **kwargs)
print 'Child: ', d, e, f, kd, ke, kf
x = Child(1, 2, 3, 4, 5, 6, ka='a', kb='b', kc='c', kd='d', ke='e', kf='f')
This unfortunately doesn't work, since 4, 5, 6 end up assigned to kd, ke, kf.
Is there some elegant python pattern for accomplishing the above?