Python:为什么我不能使用locals()修改函数中的当前作用域? [英] Python: Why can't I modify the current scope within a function using locals()?

查看:111
本文介绍了Python:为什么我不能使用locals()修改函数中的当前作用域?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么在函数中无法创建/修改locals()的成员?

Why does creating/modifying a member of locals() not work within a function?

Python 2.5 (release25-maint, Jul 20 2008, 20:47:25)
[GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2
Type "help", "copyright", "credits" or "license" for more information.

>>> # Here's an example of what I expect to be possible in a function:
>>> a = 1
>>> locals()["a"] = 2
>>> print a
2

>>> # ...and here's what actually happens:
>>> def foo():
...  b = 3
...  locals()["b"] = 4
...  print b
...
>>> foo()
3

推荐答案

为什么?它旨在返回表示形式,并且从未打算用于编辑本地人. 文档警告

Why would it? It's designed to return a representation, and was never intended for editing the locals. It's not ever guaranteed to work as a tool for such, as the documentation warns.

这篇关于Python:为什么我不能使用locals()修改函数中的当前作用域?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆