2016-12-02 69 views
-1

我已經看到文章Dynamically get dict elements via getattr?,但我無法解決我的問題。 我想做類似的事情,但我有點困惑。我想設置(不得到​​)在記者字典中的數據,但我有錯誤用getattr動態設置字典元素

AttributeError: type object 'Dicctionary' has no attribute 'VERBS'.

我的代碼是:

class Dicctionary: 
    def __init__(self): 
     self.VERBS = dict() 
     self.REFERENCER = dict() 

    def setDictionary(self, fileDictionary, name): 
     methodCaller = Dicctionary() 
     dictionary = "self."+name.upper() 
     dictionary = getattr(Dicctionary, name.upper()) 
     dictionary = fileDictionary.copy() 

你能看到我在做什麼錯?因爲我不完全明白這一點。

+0

我想你想要做的是'dictionary = getattr(methodCaller,name.upper())',但我不明白你想要達到什麼樣的目的。 – ettanany

+0

您還沒有指出哪條線路導致錯誤,也沒有足夠的代碼來重新創建錯誤,也沒有足夠的代碼以及期望的結果/輸出。 – martineau

回答

1

我認爲這是你在找什麼:

class Dicctionary: 
    def __init__(self): 
     self.VERBS = dict() 
     self.REFERENCER = dict() 

    def setDictionary(self, fileDictionary, name): 
     setattr(self, name.upper(), fileDictionary) 

這使用setattrself

分配fileDictionary該成員的名稱name.upper()的錯誤,在問題的代碼有嘗試訪問不存在的類上的名稱而不是它存在的實例的結果。

也可以寫的方法:

def setDictionary(self, fileDictionary, name): 
    dictionary = getattr(self, name.upper()) 
    dictionary.update(fileDictionary) 

這可能是更接近你正在嘗試什麼。

請注意,如果傳遞的字典發生了變化,這兩個行爲會有所不同。第一個將對象綁定到實例上的名稱。第二個使用傳入字典中的項目更新現有字典。