【问题标题】:Python __init__(self,**kwargs) takes 1 positional argument but 2 were given [duplicate]Python __init__(self,**kwargs) 采用 1 个位置参数,但给出了 2 个 [重复]
【发布时间】:2017-10-26 06:16:40
【问题描述】:

我正在 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}})

我的代码返回错误:

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

我希望 Test.group2.property4 返回 200

我发现了许多类似的问题,但主要问题是 init 方法中没有“self”。但我有。

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

【问题讨论】:

  • 您告诉__init__ 采用任意数量的关键字参数,但使用两个位置参数调用它(其中一个由 Python 隐式提供作为对创建的对象的引用,另一个是字典)..

标签: python typeerror


【解决方案1】:

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

MyClass(**{"group1":{"property1":100, "property2":200},\
    "group2":{"property3":100, "property4":200}})

【讨论】:

  • 等效:MyClass(group1={"property": 100, ...)
  • 谢谢。然后它出现在“self.b = kwargs[a][b]”行上的 KeyError 'g' 所以它不想在字典旁边打开一个字典。此外,如果我尝试在代码中只保留一个 for 循环,则 dir(MyClass) 返回 (... a) 而不是 (...group1, group2)。这意味着 self.a 在初始化时不会将自己转换为 self.group1。
  • 您建议的代码是否适合您,或者它也会给出 KeyError? MyClass(**{"group1":{"property1":100, "property2":200},\ "group2":{"property3":100, "property4":200}})
  • 问题不在于那行代码。它与 for 循环有关。 for b in a 应该是 for b in kwargs[a],因为 a 是键而不是字典。您的代码还有其他问题...
  • 结果我发现可以使用:Class MyClass(object): def __init__(self, **kwargs): for key, value in kwargs.items(): val = value if isinstance(val, dict): val = MyClass(**val) setattr(self,key,val) init 嵌套字典到 kwargs
猜你喜欢
  • 1970-01-01
  • 2021-01-16
  • 2019-01-06
  • 1970-01-01
  • 1970-01-01
  • 2022-10-06
  • 1970-01-01
  • 2013-10-28
  • 2020-05-20
相关资源
最近更新 更多