如何获取字符串中给定名称的变量的值? [英] How to get the value of a variable given its name in a string?

查看:38
本文介绍了如何获取字符串中给定名称的变量的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

def foo(a):# 我想打印变量的值# 其名称包含在一个

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

function foo($a) {回声 $$a;}全局 $string = "blah";//可能不需要是全局的,但这无关紧要foo("字符串");//打印等等"

有没有办法做到这一点?

解决方案

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

<预><代码>>>>一 = 5>>>全局变量()['a']5

关于各种eval"解决方案的注意事项:您应该小心使用 eval,尤其是如果您正在评估的字符串来自可能不受信任的来源——否则,您最终可能会删除磁盘的全部内容或如果您收到恶意字符串,则类似这样的事情.

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

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?

解决方案

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

这篇关于如何获取字符串中给定名称的变量的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆