社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

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

Phoenix • 4 年前 • 628 次点击  

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

没什么,我试过了,好像没用。我尝试使用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
 
628 次点击  
文章 [ 1 ]  |  最新文章 4 年前
modesitt
Reply   •   1 楼
modesitt    5 年前

从设计的角度来看,这似乎有点不确定,但下面是:

import views

from . import views

因为你的进口似乎与你的 PYTHONPATH .

for name, entity in views.__dict__.items():
    if not name.startswith('__'):
        cls = entity
        print(cls.get_view_type())

您可以在上添加更多条件 cls (就像它是某种以太的一个亚型 ViewClass 或者别的什么)。更好的方法是在视图文件的底部有一个列出所有类的列表,您只需导入该列表,而不必处理模块的内部表示。