简体   繁体   中英

Python New-style Classes and the Super Function

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?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM