简体   繁体   English

在__init__中打开** kwargs

[英]Unpacking **kwargs in __init__

I've stripped down my problem into the simplest possible code: 我将问题简化为最简单的代码:

class Billy:
    def __init__(self, **kwargs):
        pass

Billy({'a': 1,  'b': 2})

This is in python 3.4.3 and 2.7.6, and I have code that looks identical to this in other scripts that are working just fine. 这是在python 3.4.3和2.7.6中,并且我的代码看起来与在其他脚本中正常工作的代码相同。 I'm pulling my hair out trying to understand what it wrong here. 我正在拔头发试图了解这里的问题。 It keeps giving me a TyperError complaining that I'm using the wrong number of arguments: 它一直给我一个TyperError,抱怨我使用了错误数量的参数:

TypeError: __init__() takes 1 positional argument but 2 were given

Try adding ** : 尝试添加**

>>> Billy(**{'a': 1,  'b': 2})
<__main__.Billy object at 0x00000000023E29B0>

The confusion here is that {'a': 1, 'b': 2} is a single entity which is supplied to the constructor as the first argument, thus it's a positional argument. 这里的混乱之处在于{'a': 1, 'b': 2}是作为第一个参数提供给构造函数的单个实体,因此它是一个位置参数。 You will need to either add *args 您将需要添加*args

class Billy:
    def __init__(self, *args, **kwargs):
        pass

or supply it as Billy(a=1, b=2) or do what TigerhawkT3 suggests, adding ** to unpack the dictionary. 或将其提供为Billy(a=1, b=2)或按照TigerhawkT3的建议进行操作,并添加**以解压缩字典。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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