开发者

Python New-style Classes and the Super Function

开发者 https://www.devze.com 2022-12-28 20:52 出处:网络
This is not the result I expect to see: class A(dict): def __init__(self, *args, **kwargs): self[\'args\'] = args

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(开发者_如何学GoA):
    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
0

精彩评论

暂无评论...
验证码 换一张
取 消