locals() 有两种情况:
(1) 如果在函数内部使用 locals(),那么会以字典的形式返回函数内部定义的变量,如下例1
(2) 如果在函数外部使用 locals(),那么会以字典的形式返回全局变量和内置变量,如下例2
[root@localhost ~]$ cat 1.py #!/usr/bin/env python def fun(): x = 10 y = 20 print locals() fun()
[root@localhost ~]$ python 1.py {'y': 20, 'x': 10}
[root@localhost ~]$ cat 2.py #!/usr/bin/env python a = 10 b = 20 def fun(): c = 30 d = 40 fun() print locals()
[root@localhost ~]$ python 2.py {'a': 10, 'b': 20, '__builtins__': <module '__builtin__' (built-in)>, '__file__': '2.py',
'__package__': None, 'fun': <function fun at 0x7f849af41de8>, '__name__': '__main__', '__doc__': None}