如何获取字符串中给定名称的变量的值?

发布于 2025-01-08 13:26:16 字数 378 浏览 0 评论 0原文

为简单起见,这是我想要做的事情的精简版本:

def foo(a):
    # I want to print the value of the variable
    # the name of which is contained in a

我知道如何在 PHP 中执行此操作:

function foo($a) {
    echo $$a;
}

global $string = "blah"; // might not need to be global but that's irrelevant
foo("string"); // prints "blah"

有什么方法可以执行此操作吗?

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:

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

拍不死你 2025-01-15 13:26:16

如果它是一个全局变量,那么你可以这样做:

>>> a = 5
>>> globals()['a']
5

关于各种“eval”解决方案的注释:你应该小心 eval,特别是如果你正在评估的字符串来自潜在的不受信任的来源 - 否则,你可能最终会如果您收到恶意字符串,则删除磁盘的全部内容或类似的操作。

(如果它不是全局的,那么您将需要访问它定义的任何名称空间。如果您没有,您将无法访问它。)

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.

(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.)

弃爱 2025-01-15 13:26:16

爱德华·洛珀的答案仅在变量位于当前模块中时才有效。要获取另一个模块中的值,可以使用 getattr

import other
print getattr(other, "name_of_variable")

https://docs.python.org/3/library/functions.html#getattr

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:

import other
print getattr(other, "name_of_variable")

https://docs.python.org/3/library/functions.html#getattr

我的影子我的梦 2025-01-15 13:26:16

假设您知道该字符串可以安全评估,则 eval 将给出当前上下文中变量的值。

>>> string = "blah"
>>> string
'blah'
>>> x = "string"
>>> eval(x)
'blah'

Assuming that you know the string is safe to evaluate, then eval will give the value of the variable in the current context.

>>> string = "blah"
>>> string
'blah'
>>> x = "string"
>>> eval(x)
'blah'
南烟 2025-01-15 13:26:16
>>> x=5
>>> print eval('x')
5

多达!

>>> x=5
>>> print eval('x')
5

tada!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文