如果应使用列表或变量调用模块,则如何调用Python中模块的函数?
我有一个模块,在模块中是一个子组件,其中包含众多函数。我需要迭代包含模块名称的名称列表并调用函数。这行不通,“因为模块没有属性列表”。我如何使列表[x]可callable作为模块的子组件,而不是“列表”名称。
文件1:
def x():
print('x')
def y():
print('y')
def z():
print('z')
文件2:
import module # containing functions x(),y(),z()
list = ['x','y','z']
for x in list:
module.list[x]()
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.
file 1:
def x():
print('x')
def y():
print('y')
def z():
print('z')
file 2:
import module # containing functions x(),y(),z()
list = ['x','y','z']
for x in list:
module.list[x]()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
getaTtr()
尝试
Try
getattr()
:Prints:
您可以使用
getAttr
访问模块的“内容”。使用
to to to to in IntoSpect”模块的内容:dir
dir使用
getAttr
和hasattr
的另一种方法:也可以使用字典理解来完成:
You can use
getattr
to access to the "content" of the module.Using
dir
to "introspect" the content of the module:Another way using
getattr
andhasattr
:It can be done also using a dictionary comprehension:
您为什么不只是将函数存储在列表中?
Why don't you just store the functions in the list?