views:

151

answers:

2

This is not the result I expect to see:

class A(dict):
    def __init__(self, *args, **kwargs):
        self['args'] = args
        self['kwargs'] = kwargs

class B(A):
    def __init__(self, *args, **kwargs):
        super(B, self).__init__(args, kwargs)

print 'Instance A:', A('monkey', banana=True)
#Instance A: {'args': ('monkey',), 'kwargs': {'banana': True}}

print 'Instance B:', B('monkey', banana=True)
#Instance B: {'args': (('monkey',), {'banana': True}), 'kwargs': {}}

I'm just trying to get classes A and B to have consistent values set. I'm not sure why the kwargs are being inserted into the args, but I'm to presume I am either calling __init__() wrong from the subclass or I'm trying to do something that you just can't do.

Any tips?

+7  A: 

Try this instead:

super(B, self).__init__(*args, **kwargs)

Since the init function for A is expecting actual args/kwargs (and not just two arguments), you have to actually pass it the unpacked versions of args/kwargs so that they'll be repacked properly.

Otherwise, the already-packed list of args and dict of kwargs gets re-packed as just an args list with two elements, and an empty kwargs dict, due to the fact that you're passing a list and a dict, instead of actual unnamed and named parameters.

Amber
omg wow. i feel really stupid now. was it *that* simple!!? yes! it worked! thank you so much!
sfjedi
+1  A: 

While I agree entirely with Dav, are you aware that if the __init__ of B has no other purpose than invoking its super, you can safely omit it? What I mean is that with your examples you could simply define B as

>>> class B(A):
...      pass
krawyoti
yes. i am aware of that. thank you. i was looking to extend the __init__ functionality though.
sfjedi