Py学习  »  Python

如何循环访问python中特定文件的所有导入?

Phoenix • 5 年前 • 1381 次点击  

我正在处理一个项目,在这个项目中,我必须从所有导入的类中调用变量中的值。实现它的一种方法是手动编写类名,但是我想知道是否有某种方法,我们可以迭代它。

没什么,我试过了,好像没用。我尝试使用iter_modules(),但得到了一个attributeError。以下是问题的示例:

假设我有一个文件夹视图,其中我在不同的文件中定义了10个不同的视图类, 初始化 .py在视图文件夹中,如图所示:

from .view1 import ViewClass1
from .view2 import ViewClass2
from .view3 import ViewClass3
from .view4 import ViewClass4
.
.
.
from .view10 import ViewClass10

现在,我在我的基本文件夹中需要调用所有的viewClasses,我有如下代码:

from .views import *
# Should import all the ViewClasses ie ViewClass1, ViewClass2 and so on

# I have to call the staticmethod get_view_type defined in all the classes
# One way is:
# print(ViewClass1.get_view_type())
# print(ViewClass2.get_view_type())...
# The above continues

# But I want a solution where I can loop through all the imports from the views __init__ and call the method as:
# for viewclass in [Something]:
#     print(viewclass.get_view_type())

我想知道是否有什么方法可以做到这一点?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/38601
 
1381 次点击  
文章 [ 1 ]  |  最新文章 5 年前