2012-11-24 66 views
0

Python中是否有任何其他方法可以將字符串更改爲變量? 例如,我有一些名爲button1,button2,button3等的變量。我想在循環中對它們進行操作。如果我不想使用eval,其他任何適合的?python字符串和變量

回答

1

globalslocals它們返回當前命名空間的字典映射。如果變量是在模塊級別定義

a = 1 
print globals()['a'] #1 

globals應使用

例如: - ,locals應該用於一切。在你的情況下,我認爲locals()['button1']會做到這一點。


話雖如此,只是把按鈕放在字典中是一個更好的主意。

+0

謝謝。我認爲把它們放在字典裏是一個很好的解決方案。 – abcazx

+0

如果您對可能出現的問題留下評論,我很樂意提高這個答案:) – mgilson

+0

對不起,這麼晚了。再次感謝你。我已經解決了它。 – abcazx

0

這不是你問什麼,但什麼是錯的:

for btn in (button1, button2, button3): 
     do_something(btn) 
-1

globals()和函數返回的字典,你可以用它來直接處理全局和局部變量:

# sets the global variable foo (in the scope of the module) to 1 
# equivalent to 
# foo = 1 
# outside a functions 
globals()['foo'] = 1 

# gets the local variable bar (in the scope of the current function) 
# equivalent to 
# print bar 
# inside a function 
print locals()['bar'] 

當您在功能之外使用locals()時,它將等同於使用globals()

如果你想操作一個對象的屬性,你可以使用getattr(obj, name)setattr(obj, name, value)代替:

# equivalent to 
# print foo.x 
print getattr(foo, 'x') 

# equivalent to 
# foo.x = 45 
setattr(foo, 'x', 45) 

編輯:由於DSM指出,使用locals()不能可靠地用於設置函數中的變量值。無論如何,將單獨的字典中的所有按鈕都包含在內,也會更聰明。

+1

你不能依靠這種方式修改'locals()',因爲[docs](http://docs.python.org/2/library/functions.html#locals)警告。嘗試在函數中更改'bar'並在'locals()['bar']'賦值之前和之後粘貼'print bar'。 – DSM