且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Python中导入变量包,例如在PHP中使用变量变量($$)?

更新时间:2023-11-25 08:08:16

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