2017-05-25 30 views
1

我創建在Python 3.6的簡單類應該接受一個字典作爲參數鍵,值Python的__init __(自我,** kwargs)需要1周位置的說法,但2被賦予

我的代碼:

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() takes 1 positional argument but 2 were given

我希望Test.group2.property4返回200

有很多類似的問題,但我發現無論在哪裏都存在主要問題是init方法中缺少「自我」。但我擁有它。

有人可以解釋這個錯誤的原因嗎? 感謝

+0

你叫'__init__'採取關鍵字參數任意數字,但是有兩個位置叫它參數(其中一個由Python隱式提供,作爲創建對象的引用,另一個是字典)。 – timgeb

回答

4

傳遞參數(S)爲解壓縮字典,而不是作爲一個單獨的位置參數:

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

等價物:'MyClass(group1 = {「property」:100,...)' – mdurant

+0

謝謝。然後它出現在「self.b = kwargs [a] [b]」上的KeyError'g' 因此它不想在字典中打開字典。 另外,如果我試圖在代碼中留下一個for循環,則dir(MyClass)返回(... a)而不是(... group1,group2)。這意味着self.a在初始化時不會將其自身轉換爲self.group1。 – Dant

+0

您的建議代碼是否適合您,或者它也會產生KeyError? MyClass(** {「group1」:{「property1」:100,「property2」:200},\ 「group2」:{「property3」:100,「property4」:200}}) – Dant

相關問題