作用
locals()
函数会以字典类型返回当前位置的全部局部变量。对于函数, 方法, lambda
函式, 类, 以及实现了 __call__
方法的类实例, 它都返回 True
。
In [27]: locals()
<h2><strong>返回值</strong></h2>
返回字典类型的局部变量。
<pre class="lang:python decode:true " >In [27]: locals()
Out[27]:
{'In': ['',
u"get_ipython().magic(u'cls ')",
u'def foo():\n c = 1\n def inner():\n x += 1\n return x\n return foo',
u'print foo',
u'print foo()()',
u'def foo():\n c = 1\n def inner():\n c += 1\n return c\n return foo',
u'def foo():\n c = 1\n def inner():\n c += 1\n return c\n return inner',
u'def foo():\n c = 1\n def inner():\n c += 1\n return c\n return inner',
u'print foo()()',
u'print foo()',
u'help()',
u'c = 1',
u'def foo():\n global c\n c = 1\n def inner():\n c += 1\n return c\n return inner',
u'print foo()()',
u'def foo():\n global c\n c = 1\n def inner():\n global c\n c += 1\n return c\n return inner',
u'print foo()()',
u'print locals()',
u'def a():\n x =0\n def b():\n y = x +1 \n print locals()\n print x,y\n return b',
....
In [30]: type(locals())
Out[30]: dict
In [31]: def foo():
...: z = 1
...: return locals()
...:
In [32]: foo()
Out[32]: {'z': 1}