标签:
示例代码:
1 def test(arg): 2 a=1 3 b=2 4 data_dict = {} 5 print locals() 6 print globals() 7 8 9 if __name__ == ‘__main__‘: 10 test(3)
输出为:
1 {‘a‘: 1, ‘data_dict‘: {}, ‘b‘: 2, ‘arg‘: 3} 2 {‘__builtins__‘: <module ‘__builtin__‘ (built-in)>, ‘__file__‘: ‘F:/work/workspace/pythonWorkspace/learn/locals_globals.py‘, ‘__package__‘: None, ‘test‘: <function test at 0x0239F830>, ‘__name__‘: ‘__main__‘, ‘__doc__‘: None}
示例代码:
1 b = 5 # 定义一个全局变量 2 def test2(): 3 a=1 4 locals()["a"] = 2 # 修改局部变量 5 print "a=", a 6 globals()["b"] = 6 # 修改全局变量 7 print "b=", b 8 9 if __name__ == ‘__main__‘: 10 test2()
输出为:
a= 1
b= 6
标签:
原文地址:http://www.cnblogs.com/shanys/p/5887023.html