This question already has an answer here:
这个问题在这里已有答案:
- How do I create a variable number of variables? 12 answers
- 如何创建可变数量的变量? 12个答案
For simplicity this is a stripped down version of what I want to do:
为简单起见,这是我想要做的精简版:
def foo(a):
# I want to print the value of the variable
# the name of which is contained in a
I know how to do this in PHP:
我知道如何在PHP中执行此操作:
function foo($a) {
echo $$a;
}
global $string = "blah"; // might not need to be global but that's irrelevant
foo("string"); // prints "blah"
Any way to do this?
有什么办法吗?
4 个解决方案
#1
60
If it's a global variable, then you can do:
如果它是一个全局变量,那么你可以这样做:
>>> a = 5
>>> globals()['a']
5
A note about the various "eval" solutions: you should be careful with eval, especially if the string you're evaluating comes from a potentially untrusted source -- otherwise, you might end up deleting the entire contents of your disk or something like that if you're given a malicious string.
关于各种“eval”解决方案的注意事项:你应该小心eval,特别是如果你正在评估的字符串来自可能不受信任的来源 - 否则,你最终可能会删除磁盘的全部内容或类似的东西如果给你一个恶意字符串。
(If it's not global, then you'll need access to whatever namespace it's defined in. If you don't have that, there's no way you'll be able to access it.)
(如果它不是全局的,那么你将需要访问它所定义的任何命名空间。如果你没有,那么你将无法访问它。)
#2
22
Edward Loper's answer only works if the variable is in the current module. To get a value in another module, you can use getattr
:
Edward Loper的答案仅在变量位于当前模块中时才有效。要在另一个模块中获取值,可以使用getattr:
import other
print getattr(other, "name_of_variable")
https://docs.python.org/2/library/functions.html#getattr
https://docs.python.org/2/library/functions.html#getattr
#3
10
>>> string = "blah"
>>> string
'blah'
>>> x = "string"
>>> eval(x)
'blah'
#4
4
>>> x=5
>>> print eval('x')
5
tada!
田田!
#1
60
If it's a global variable, then you can do:
如果它是一个全局变量,那么你可以这样做:
>>> a = 5
>>> globals()['a']
5
A note about the various "eval" solutions: you should be careful with eval, especially if the string you're evaluating comes from a potentially untrusted source -- otherwise, you might end up deleting the entire contents of your disk or something like that if you're given a malicious string.
关于各种“eval”解决方案的注意事项:你应该小心eval,特别是如果你正在评估的字符串来自可能不受信任的来源 - 否则,你最终可能会删除磁盘的全部内容或类似的东西如果给你一个恶意字符串。
(If it's not global, then you'll need access to whatever namespace it's defined in. If you don't have that, there's no way you'll be able to access it.)
(如果它不是全局的,那么你将需要访问它所定义的任何命名空间。如果你没有,那么你将无法访问它。)
#2
22
Edward Loper's answer only works if the variable is in the current module. To get a value in another module, you can use getattr
:
Edward Loper的答案仅在变量位于当前模块中时才有效。要在另一个模块中获取值,可以使用getattr:
import other
print getattr(other, "name_of_variable")
https://docs.python.org/2/library/functions.html#getattr
https://docs.python.org/2/library/functions.html#getattr
#3
10
>>> string = "blah"
>>> string
'blah'
>>> x = "string"
>>> eval(x)
'blah'
#4
4
>>> x=5
>>> print eval('x')
5
tada!
田田!