Fork me on GitHub

python学习--locals globals

python学习--locals globals

locals() and globals()

locals()globals()是python的两个内置函数,它们提供了基于dictionary的访问局部和全局变量的方式。 locals()返回一个名字/值对的dictionary。这个dictionary的键字是字符串形式的变量名字,diction的值是变量的实际值。

In [12]: def func(arg):
    ...:     num = 90
    ...:     print locals()
    ...:     print locals()['arg']
    ...:     

In [13]: func('hello')
{'num': 90, 'arg': 'hello'}
hello

globals()函数则返回包含全局变量的dictionary,在下例中,operation()函数根据oper变量的值自动调用相应的全局函数:

In [3]: def plus(a,b):
   ...:     return a+b
   ...: 

In [4]: def minus(a,b):
   ...:     return a-b
   ...: 

In [5]: def operation(oper,a,b):
   ...:     oper = 'plus' if oper=='+' else 'minus'
   ...:     return globasl()[oper](a,b)
   ...: 
In [7]: def operation(oper,a,b):
   ...:     oper = 'plus' if oper=='+' else 'minus'
   ...:     return globals()[oper](a,b)
   ...: 

In [8]: operation('+',2,3)
Out[8]: 5

In [9]: operation('-',2,3)
Out[9]: -1

locals是只读的,globals不是

In [15]: def func():
    ...:     num = 1
    ...:     print locals()
    ...:     locals()['num'] = 3 #无法修改num
    ...:     print "num =",num
    ...:     

In [16]: func()
{'num': 1}
num = 1
In [18]: x = 7

In [19]: print "x =",x
x = 7

In [20]: globals()["x"] = 8 #可以修改x

In [21]: print "x =",x
x = 8

转载请注明出处:BackNode

My zhiFuBao

Buy me a cup of coffee

blogroll

social