如何在Python中导入变量包,例如在PHP中使用变量变量($$)? [英] How do I import variable packages in Python like using variable variables ($$) in PHP?

查看:175
本文介绍了如何在Python中导入变量包,例如在PHP中使用变量变量($$)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想根据用户选择的值导入一些软件包.

I want to import some package depending on which value the user chooses.

默认值为file1.py:

from files import file1

如果用户选择file2,则应为:

If user chooses file2, it should be :

from files import file2

在PHP中,我可以使用变量变量:

In PHP, I can do this using variable variables:

$file_name = 'file1';
include($$file_name);

$file_name = 'file2';
include($$file_name);

如何在Python中做到这一点?

How can I do this in Python?

推荐答案

Python没有与PHP的变量变量"直接等效的功能.要获取变量变量"的值(或任何其他表达式的值),可以使用eval函数.

Python doesn't have a feature that's directly equivalent to PHP's "variable variables". To get a "variable variable"'s value (or the value of any other expression) you can use the eval function.

foo = "Hello World"
print eval("foo")

但是,不能在import语句中使用它.

However, this can't be used in an import statement.

可以使用 __import__ 函数来使用变量.

It is possible to use the __import__ function to import using a variable.

package = "os"
name = "path"

imported = getattr(__import__(package, fromlist=[name]), name)

等同于

from os import path as imported

这篇关于如何在Python中导入变量包,例如在PHP中使用变量变量($$)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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