如何在Python中列出已导入的类? [英] How do I make a list of imported classes in Python?
问题描述
from module import a, b, c
foo(a)
foo(b)
foo(c)
是否有一种方法可以避免必须为每个导入的对象调用 foo(x)
?
Is there a way to avoid having to call foo(x)
for each imported object?
某些上下文:a,b,c是网页类,而foo是route()函数,该函数为每个网页创建路由.
Some context: a, b, c are webpage classes and foo is a route() function that creates a route for each webpage.
更新:随着应用程序的增长,主模块中的导入类列表将越来越多.我仅以a,b和c为例.我正在寻找类似 import a,b,c到classes_list
之类的东西,然后可以遍历 classes_list
而不是在每个导入的类上调用foo.
Update: There will be a growing list of imported classes in the main module as the application grows. I mentioned a, b, and c simply as an example. I am looking for something like import a, b, c to classes_list
and then I can iterate over the classes_list
instead of calling foo on each of the imported classes.
推荐答案
假设没有其他导入,则可以遍历globals().items()来收集所有类.如果您在整体导入中还有其他类,则可能需要进一步过滤.
Assuming you have no other imports, you could iterate over globals().items() to gather all the classes. You may need to filter further if there are additional classes in your overall imports.
import inspect
from pandas import DataFrame, Grouper, ExcelFile
imps = globals().items()
filtered_imps = [x[1] for x in imps if inspect.isclass(x[1])]
print(filtered_imps)
产生:
[<class '_frozen_importlib.BuiltinImporter'>, <class 'pandas.core.frame.DataFrame'>, <class 'pandas.core.groupby.grouper.Grouper'>, <class 'pandas.io.excel._base.ExcelFile'>]
然后,您可以根据需要在循环中或作为理解的一部分在列表中 foo()
,也许可以使用 try ... except
来处理异常在途中.
Then you can foo()
over the list as necessary in a loop or as part of the comprehension, perhaps using a try ... except
to deal with exceptions on the way.
这篇关于如何在Python中列出已导入的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!