2016-12-21 45 views
3

Atom api是Enaml用來實現MVC的庫。更改原子var,並更新UI。在UI中更改它,並更新模型。Python Atom API:使用字典時如何設置atom var

我想提出(在這種情況下,布爾())一個Atom變種成一本字典,後來更新變種

from atom.api import Atom,Bool 
class MyModel(Atom): 
    myBool = Bool() 

    def getDict(self): 
     return {'mybool':self.myBool} 

    def setAllBoolsTrue(self): 
     self.myBool = True #example to show that just setting mybool will update UI components that use it 

     #now to show how I'd like to generalize to many components 

     for k,v in self.getDict().iteritems(): 
      v = True # this fails, even though the id(v) is the same as id(self.mybool) 

最後聲明未能更新mybool,它只是做一個簡單的任務。

那麼有沒有一種方法來更新從字典中檢索的Bool(),就像簡單地設置它一樣?

編輯:代碼更新,所以沒有語法錯誤。

編輯:在

tempDict = self.getDict(); 
    #self.myBool = True # this works 
    tempDict['mybool'] = True #this does not work 
+2

我簡直要瘋了,但是這看起來像你試圖重新分配地方變量(副本)。您可能需要使用'set'操作修改字典。 – Carcigenicate

+1

您的代碼至少有一個語法錯誤,請確保您發佈的內容是[MCVE]。你對Python OOP有多熟悉?多件事情有點關閉......而你的具體問題是名字'v'正在被反彈;相反,您需要存儲該詞典並將其改爲循環。除了所有其他問題外, 'tmpdict = getDict();對於tmpdict中的k:tmpdict [k] = True'。 –

+0

你是對的@Carcigenicate,一個簡單的變量賦值正在發生。本地var和myBool的id()是相同的。有沒有可以調用來更新原始變量的函數?我會看看集合。 –

回答

0

從凌動開發者之一聽證會後,答案是SETATTR正確使用。我曾試圖在布爾()本身使用SETATTR,但是需要使用它的子類的Atom,如下所示:

from atom.api import Atom,Bool 
class MyModel(Atom): 
    myBool = Bool() 

    def getDict(self): 
     return {'myBool':self.myBool} 

    def setAllBoolsTrue(self): 
     self.myBool = True #example to show that just setting mybool will update UI components that use it 

     #now to show how to generalize to many components 

     for key,value in self.getDict().iteritems(): 
      setattr(self,key,True) #this updates the UI 
+0

這看起來與setattr的非Atom應用程序完全相同;) –

0

for k, v in getDict():不會工作,除非你getDict()函數返回兩個按鍵的字典,即k, v會更貼切地命名爲key1, key2:按照在意見建議,我嘗試沒有成功這種情況下,其中key2甚至不存在。


如果你真的想要實現類,你可以這樣做......

class MyModel(Atom): 

    def __init__(self): 
     self.myBool = True 


>>> model = MyModel() 
>>> model.myBool 
True 
>>> model.myBool = False 
>>> model.myBool 
False 
+0

@Carcigenicate,但它不:它會返回一個字典,如你所見。迭代一個字典給你的鑰匙。我想,迭代關鍵值對不是python 2/3 polyglot。 –

+0

我喜歡立即downvote後我張貼。任何人想解釋我爲什麼錯了? – moogle

+0

主要原因是這是一個很難形成的問題,因爲它裏面的代碼是不一致和錯誤的, OP沒有辦法使用它。在清理之前,嘗試調試它是沒有用的。 *但是*,OP的實際問題是關於改變字典,你的回答沒有幫助。你在代碼中選擇了一個錯誤(從少數幾個中)並且解決了它*錯誤*:對於k,沒有辦法','中的v將會起作用。 *而且*我曾看到你發表過難以回答的問題來公然討論題外話題。給我一個理由,爲什麼我*不應該*失望。 –