本文主要是介绍Python中globals和locals的区别,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
def foo(arg, a):
x = 1
y = 'xxxxxx'
for i in range(10):
j = 1
k = i
print locals()
#调用函数的打印结果
foo(1,2)
#{'a': 2, 'i': 9, 'k': 9, 'j': 1, 'arg': 1, 'y': 'xxxxxx', 'x': 1}
Python的两个内置函数,locals 和globals,它们提供了基于字典的访问局部和全局变量的方式。
1、locals()是只读的。globals()不是。这里说的只读,是值对于原有变量的只读。其实还可以对locals()赋值的。见下图

上面的图就可以看出了,对locals()中增加了一个b变量。
locals()和globals()在作用域上的区别
正如它们的命名,locals()返回的是局部变量,globals()返回的是全局变量.
这个差异在函数中就比较容易发现了,建议自己编写函数试试.
| 1 2 3 4 5 6 7 | >>> def a(): ... b=1 ... print locals(),globals() ... >>> a() {'b': 1} {'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main __', '__doc__': None, 'a': <function a at 0x01A8A6B0>, '__package__': None} |
locals()和globals()在访问性上的区别
我们先来看一段简单的脚本吧.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | >>> a=1 >>> b=globals() >>> print globals() {'a': 1, 'b': {...}, '__builtins__': <module '__builtin__' (built-in)>, '__packa ge__': None, '__name__': '__main__', '__doc__': None} >>> a=2 >>> print b {'a': 2, 'b': {...}, '__builtins__': <module '__builtin__' (built-in)>, '__packa ge__': None, '__name__': '__main__', '__doc__': None} >>> b['a']=3 >>> print globals() {'a': 3, 'b': {...}, '__builtins__': <module '__builtin__' (built-in)>, '__packa ge__': None, '__name__': '__main__', '__doc__': None} >>> print a 3 |
可以看出globals()返回的是当前全局变量的引用,而且可以通过修改b['a']来改变变量a的值.
所以globals()的返回值是可读可写的.
2、locals和globals的返回不同
locals(...)
locals() -> dictionary
Update and return a dictionary containing the current scope's local variables.
globals(...)
globals() -> dictionary
Return the dictionary containing the current scope'sglobal variables.
记住,locals返回的变量都是原有变量的“拷贝”。
让我们再来看一段脚本:
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | >>> def a(): ... b=1 ... c=locals() ... print c ... b=2 ... print locals() ... print c ... c['b']=3 ##在locals()中试图修改b的值,失败了. ... print locals() ... print b ... locals()['b']=3 ... print locals() ... print b ... print c ... >>> a() {'b': 1} {'c': {...}, 'b': 2} {'c': {...}, 'b': 2} {'c': {...}, 'b': 2} 2 {'c': {...}, 'b': 2} 2 {'c': {...}, 'b': 2} |
在locals()中试图修改b的值,失败了.
在locals()的引用变量c中修改b的值,失败了.
可见locals()虽然返回的和globals()一样都是字典,但其访问性是不同的.
globals()可以直接修改其中对应键的值,而locals()做不到.
这篇关于Python中globals和locals的区别的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!