exec/eval 的替代方法? [英] Alternatives to exec/eval?

查看:64
本文介绍了exec/eval 的替代方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直试图找到一种方法来可靠地设置和获取字符串中名称的变量的值.我可以在远程找到的任何接近于此的东西似乎并不总是有效.变量可以在任何模块中,并导入这些模块.

I've been trying to find a way to reliably set and get values of variables with the names in strings. Anything I can find remotely close to this doesn't seem to always work. The variables can be in any module and those modules are imported.

获取和设置变量值的安全/正确方法是什么?

What is the safe/correct way to get and set the values of variables?

ps - 我和 Python 一样新手

ps - I'm as newb as they come to python

推荐答案

虽然它可以工作,但通常不建议使用对程序本身有意义的变量名称.

While it would work, it is generally not advised to use variable names bearing a meaning to the program itself.

相反,最好使用字典:

mydict = {'spam': "Hello, world!"}
mydict['eggs'] = "Good-bye!"
variable_name = 'spam'
print mydict[variable_name]  # ==> Hello, world!
mydict[variable_name] = "some new value"
print mydict['spam']  # ==> "some new value"
print mydict['eggs']  # ==> "Good-bye!"

(从另一个答案中获取并修改的代码)

(code taken from the other answer and modified)

这篇关于exec/eval 的替代方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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