[英]How do you call a function of a module in Python if the module should be called with a list or variable?
I have a module, in the module is a subcomponent which contains a multitude of functions.我有一个模块,模块中有一个包含多种功能的子组件。 I need to iterate through a list of names which contains the names of the modules and call the functions.我需要遍历包含模块名称的名称列表并调用函数。 this does not work, "because module has no attribute list".这不起作用,“因为模块没有属性列表”。 How do I make list[x] callable as a subcomponent of module instead of "list" the name.如何使 list[x] 可作为模块的子组件调用,而不是“列出”名称。
file 1:文件 1:
def x():
print('x')
def y():
print('y')
def z():
print('z')
file 2:文件 2:
import module # containing functions x(),y(),z()
list = ['x','y','z']
for x in list:
module.list[x]()
You can use getattr
to access to the "content" of the module.您可以使用getattr
访问模块的“内容”。
Using dir
to "introspect" the content of the module:使用dir
“内省”模块的内容:
import my_module
func_names = ['x','y','z']
callable_funcs = []
for stuffs in dir(my_module):
if stuff in func_names:
callable_funcs.append(getattr(my_module, stuff))
# make a dictionary
funcs = dict(zip(func_names, callable_funcs))
# usage
x = funcs['x']
print(x())
Another way using getattr
and hasattr
:使用getattr
和hasattr
的另一种方法:
import my_module
func_names = ['x','y','z']
callable_funcs = []
for f_name in func_names:
if hasattr(my_module, f_name):
callable_funcs.append(getattr(my_module, f_name))
# make a dictionary
funcs = dict(zip(func_names, callable_funcs))
# usage
x = funcs['x']
print(x())
It can be done also using a dictionary comprehension:也可以使用字典理解来完成:
import my_module
func_names = ['x','y','z']
funcs = {f_name: getattr(my_module, f_name) for f_name in func_names if hasattr(my_module, f_name)}
Why don't you just store the functions in the list?为什么不将函数存储在列表中?
>>> def x():
... print("x")
...
>>> def y():
... print("y")
...
>>> functions = [x, y]
>>> for f in functions:
... f()
...
x
y
>>>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.