使用字符串设置python对象/变量的名称 [英] Set the name of a python object/variable with a string

查看:204
本文介绍了使用字符串设置python对象/变量的名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大多数人可能会说这是个坏主意.我想将字符串的内容用作变量的名称.我想完成可怕的事情:

Most people will probably say this is a bad idea. I want to use the content of a string as the name of a variable. I want to accomplish the dreaded:

s = 'x'
x = 1

变量名x来自字符串s的位置(以某种方式?).

where the variable name x comes (somehow?) from the string s.

要回答为什么?",请说我有一个x的全局默认值,我希望在函数中覆盖该选项.但是:

To answer the "why?", say I have a global default value for x that I want the option of overriding in a function. But:

x = 0
def f(**kw):
    print x
f(x=1)

打印0而不是1.如果我可以使用kw.keys()中的字符串来重新分配x(或任何其他全局设置的变量),那么我会很高兴的.

prints 0 not 1. If I could use the strings in kw.keys() to reassign x (or any other globally set variables) then I'd be happy.

我意识到这可以在f中重新分配x:

I realize that this works for reassigning x in f:

x = 0
def f(x=x):
    print x
f(x=1)

但是我想在命名空间中有很多变量但有时不重写模块中的每个函数定义的情况下要覆盖的情况下执行此操作.

But I want to do this for cases where there are MANY variables in my namespace that I might at some point want to override without rewriting every function definition in my module.

推荐答案

查看 exec

>>> print x
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined
>>> s = 'x'
>>> exec(s + " = 1")
>>> print x
1 

另请参阅:如何在python中使用eval分配变量的值?

经过一些试验,这似乎也可行:

After a little experimentation, this also seems to work:

>>> print x
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined
>>> s = 'x'
>>> globals()[s] = 1
>>> print x
1

这篇关于使用字符串设置python对象/变量的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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