python怎么设置变量名,使用字符串设置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

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

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)

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.

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.

解决方案

Check out exec

>>> print x

Traceback (most recent call last):

File "", line 1, in

NameError: name 'x' is not defined

>>> s = 'x'

>>> exec(s + " = 1")

>>> print x

1

After a little experimentation, this also seems to work:

>>> print x

Traceback (most recent call last):

File "", line 1, in

NameError: name 'x' is not defined

>>> s = 'x'

>>> globals()[s] = 1

>>> print x

1

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值