python:给一个变量赋值,其名称存储在一个变量中

python: assign value to a variable whose name is stored in a variable

也许这个问题回答起来很简单,但是在网上查了半天发现很没有answer/workaround:

在 Python (v3) 中,我想执行以下操作:

def func():
    pass

foo = "bar"

# Now I would like to make an assignment to a variable named
# based on the value of foo (i.e. effectively bar = func, but using foo)
# so that:
bar() == func()  # is True
bar is func  # is also True

我该怎么做? 谢谢!

我猜问题是什么,但你在找这样的东西吗:

def func():
    pass

foo = "bar"
locals()[foo] = func

bar() == func() # True
# or better yet
bar is func # also True