本文介绍了在 Python 3.2+ 中添加到 locals()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试以编程方式在本地命名空间中定义几个变量:

for build_step in 'prepare', 'configure', 'make', 'stage', 'package', 'all':p = build_subparsers.add_parser(build_step)p.set_defaults(build_step=build_step)如果 build_step != 'package':p.add_argument('specfile')locals()['build_'+build_step+'_parser'] = pbuild_prepare_parser
NameError: 全局名称 'build_prepare_parser' 未定义

然而,在运行此代码后,尽管出现在 locals() 中,但我假定创建的变量实际上都不存在.我如何在 Python 3.2 中执行此操作?

更新0

我知道 locals() 是个坏主意,这就是我问这个问题的原因.

解决方案

答案是:不要那样做.

如果要以编程方式存储值,请使用容器:

>>>d = 字典()>>>d['a'] = 5

或者创建一个容器类,如果你真的需要的话.

>>>类容器(对象):... 经过...>>>c = 容器()>>>setattr(c, 'a', 5)>>>c.a5

I'm trying to programmatically define several variables in the local namespace:

for build_step in 'prepare', 'configure', 'make', 'stage', 'package', 'all':
    p = build_subparsers.add_parser(build_step)
    p.set_defaults(build_step=build_step)
    if build_step != 'package':
        p.add_argument('specfile')
    locals()['build_'+build_step+'_parser'] = p
build_prepare_parser
NameError: global name 'build_prepare_parser' is not defined

However after running this code, none of the variables I presumed to create actually exist despite appearing in locals(). How do I do this in Python 3.2?

Update0

I know locals() is a bad idea, that's why I'm asking this question.

解决方案

The answer is: don't do that.

If you want to programmatically store values, use a container:

>>> d = dict()
>>> d['a'] = 5

Or create a container class, if you really must.

>>> class Container(object):
...     pass
... 
>>> c = Container()
>>> setattr(c, 'a', 5)
>>> c.a
5

这篇关于在 Python 3.2+ 中添加到 locals()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-16 03:52