简体   繁体   English

Python Atom API:如何在使用字典时设置atom var

[英]Python Atom API: how to set atom var when using a dictionary

The Atom api is a library used by Enaml to implement MVC. Atom api是Enaml用来实现MVC的库。 Change an atom var, and the UI is updated. 更改atom var,并更新UI。 Change it in the UI and your model gets updated. 在UI中更改它,您的模型会更新。

I would like to put an Atom var (Bool() in this case) into a dictionary and later update that var 我想将一个Atom var(在这种情况下为Bool())放入一个字典中,然后更新该var

 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)

The last statement fails to update mybool, it just makes a simple assignment. 最后一个语句无法更新mybool,它只是简单的分配。

So is there a way to update the Bool() retrieved from a dictionary in the same way that simply setting it does? 那么有没有办法更新从字典中检索的Bool(),就像设置它一样?

edit: code updated so no syntax errors. 编辑:代码更新,所以没有语法错误。

edit: As per suggestions in the comments, I tried without success: 编辑:根据评论中的建议,我尝试没有成功:

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

for k, v in getDict(): won't work unless your getDict() function returns a dict of two keys, ie k, v would more aptly be named key1, key2 in this case, where key2 doesn't even exist. for k, v in getDict():除非你的getDict()函数返回两个键的dict,否则将无法工作,即k, v在这种情况下更适合命名为key1, key2 ,其中key2甚至不存在。


If you really want to implement classes, you can do something like... 如果你真的想要实现类,你可以做类似......

class MyModel(Atom):

    def __init__(self):
        self.myBool = True


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

After hearing from one of the Atom developers, the answer is to use setattr correctly. 在听取其中一位Atom开发人员的回复后,答案是正确使用setattr。 I had tried to use setattr on the Bool() itself, but one needs to use it on the Atom subclass, as follows: 我曾尝试在Bool()本身上使用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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM