如何将字符串转换为变量名? [英] How to convert string to variable name?
问题描述
我想知道如何将字符串输入转换为变量名以用于 Python 代码.一个具体的例子:
I would like to know how to convert a string input into a variable name to use into Python code. A concrete example:
def insrospect(foo, bar):
requested_module = makestringvariable(foo)
requested_object = makestringvariable(bar)
import requested_module
for item in inspect.getmemebers(requested_module.requested_object):
member = makestringvariable(item[0])
if callable(requested_object.member):
print item
if __name__ == '__main__':
introspect(somemodule, someobject)
所以在上面,因为我不知道在启动前要内省哪个模块,我需要将字符串转换为可用的模块名称,并且因为 getmembers()
将成员作为字符串返回,我也需要将它们转换为可用的变量名称以检查它们是否可调用.
So here above, because i do not know which module to introspect before launching, i need to convert the string to a usable module name and because getmembers()
returns the members as strings, i also need them to be converted into usable variable names to check if they are callable.
有没有这样的makestringvariable()
函数?
推荐答案
with the __import__ 函数和 getattr 魔法,你将能够直接写这个:
with the __import__ function and the getattr magic, you will be able to directly write this :
import importlib
def introspect(foo, bar):
imported_module = importlib.import_module(foo)
imported_object = getattr(imported_module, bar)
for item in inspect.getmembers(imported_object):
if callable(getattr(imported_object, item[0]):
print item
if __name__ == '__main__':
introspect(somemodule, someobject)
这篇关于如何将字符串转换为变量名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!