Python __init __(self,**kwargs)占用1个位置参数,但给出了2个

Dan*_*ant 3 python typeerror

我正在Python 3.6中创建一个简单的类,它应该接受键,字典中的值作为参数

我的代码:

class MyClass:
    def __init__(self, **kwargs):
        for a in kwargs:
            self.a=kwargs[a]
            for b in a:
                self.a.b = kwargs[a][b]
Test = MyClass( {"group1":{"property1":100, "property2":200},\
    "group2":{"property3":100, "property4":200}})
Run Code Online (Sandbox Code Playgroud)

我的代码返回一个错误:

TypeError:init()占用1个位置参数,但给出了2个

我希望Test.group2.property4返回200

我发现有很多类似的问题但是到处都存在的主要问题是在init方法中缺少"self" .但我有它.

有人可以解释这个错误的原因吗?谢谢

Mos*_*oye 9

将参数作为解压缩的dict传递,而不是作为单个位置参数传递:

MyClass(**{"group1":{"property1":100, "property2":200},\
    "group2":{"property3":100, "property4":200}})
Run Code Online (Sandbox Code Playgroud)

  • 等效:`MyClass(group1 = {“ property”:100,...)` (2认同)