2016-12-21 40 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将会起作用。 *而且*我曾看到你发表过难以回答的问题来公然讨论题外话题。给我一个理由,为什么我*不应该*失望。 –