dsa*_*avi 66 python string variables
为简单起见,这是我想要做的精简版:
def foo(a):
# I want to print the value of the variable
# the name of which is contained in a
Run Code Online (Sandbox Code Playgroud)
我知道如何在PHP中执行此操作:
function foo($a) {
echo $$a;
}
global $string = "blah"; // might not need to be global but that's irrelevant
foo("string"); // prints "blah"
Run Code Online (Sandbox Code Playgroud)
有什么办法吗?
Edw*_*per 106
如果它是一个全局变量,那么你可以这样做:
>>> a = 5
>>> globals()['a']
5
Run Code Online (Sandbox Code Playgroud)
关于各种"eval"解决方案的注意事项:你应该小心eval,特别是如果你正在评估的字符串来自可能不受信任的来源 - 否则,你最终可能会删除磁盘的全部内容或类似的东西如果给你一个恶意字符串.
(如果不是全球性的,那么你就需要访问任何的命名空间中的已定义.如果你没有这样的,有没有办法,你就可以访问它.)
ere*_*nce 42
Edward Loper的答案仅在变量位于当前模块中时才有效.要在另一个模块中获取值,您可以使用getattr
:
import other
print getattr(other, "name_of_variable")
Run Code Online (Sandbox Code Playgroud)
https://docs.python.org/2/library/functions.html#getattr
sta*_*ark 16
>>> string = "blah"
>>> string
'blah'
>>> x = "string"
>>> eval(x)
'blah'
Run Code Online (Sandbox Code Playgroud)
>>> x=5
>>> print eval('x')
5
Run Code Online (Sandbox Code Playgroud)
田田!