前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >连仕彤博客[Python笔记] locals() 函数

连仕彤博客[Python笔记] locals() 函数

作者头像
行 者
发布2018-06-13 14:42:22
2720
发布2018-06-13 14:42:22
举报
文章被收录于专栏:运维技术迷

作用

locals() 函数会以字典类型返回当前位置的全部局部变量。对于函数, 方法, lambda 函式, 类, 以及实现了 __call__ 方法的类实例, 它都返回 True

语法

代码语言:javascript
复制
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

示例

代码语言:javascript
复制
In [31]: def foo():
    ...:     z = 1
    ...:     return locals()
    ...:
 
In [32]: foo()
Out[32]: {'z': 1}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 语法
  • 示例
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档