Python New Style Classes and Super Function

This is not the output 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 am just trying to get classes A and B to set consistent values. I'm not sure why the kwargs are being inserted into args, but I have to assume that I am either calling __init__()

wrong from the subclass or trying to do something that you simply cannot do.

Any advice?

+2


a source to share


2 answers


Try this instead:

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

      



Since the init function for A expects actual args / kwargs arguments (not just two arguments), you must actually pass unpacked versions of args / kwargs to them so that they are repackaged correctly.

Otherwise the already packed list of args and dict of kwargs will be repackaged as just a list of args with two elements, and an empty kwargs dict, due to the fact that you are passing the list and dict, instead of the actual unnamed and named parameters.

+14


a source


While I totally agree with Dove, did you know that if __init__

of B has no other purpose than calling super, you can safely omit it? I mean, with your examples, you can simply define B as



>>> class B(A):
...      pass

      

+2


a source







All Articles