2014-02-18 111 views
0

查找到下面的示例中的全局变量..Python的访问使用全局变量()

var1 = 10 
var2 = "String" 
var3 = True 
dic = {} 

def func1(): 
    ... 
    ... 

def main(): 
    varN = globals().["var1"] 
    Dictionary = globals().["dic"].var2('some other string') 

如何阅读本?全局变量()?这是如何被使用和解释?

请帮忙。谢谢。

回答

1

globals()返回字典。

print type(globals()) # <type 'dict'> 

因此,下标符号足以访问全局变量。

print globals()["var1"] 
globals()["dic"][var2] = 'some other string' 
print dic # {'String': 'some other string'} 
+0

啊,好理解。非常感谢。 – Bala