模块的Python目录结构

问题描述 投票:0回答:2

我在当前目录中有以下目录和文件结构:

├── alpha
│   ├── A.py
│   ├── B.py
│   ├── Base.py
│   ├── C.py
│   └── __init__.py
└── main.py

alpha /目录下的每个文件都是它自己的类,每个类都在Base.py中使用Base类。现在,我可以在main.py中做这样的事情:

from alpha.A import *
from alpha.B import *
from alpha.C import *

A()
B()
C()

它工作正常。但是,如果我想添加一个文件和类“D”,然后在main.py中使用D(),我必须进入我的main.py并执行“from alpha.D import *”。反正有没有在我的主文件中导入,以便它导入alpha目录下的一切?

python class module directory-structure
2个回答
0
投票

好问题!我在google搜索后找到this SO post的答案:“python import complete directory。”

希望有所帮助!


0
投票

取决于你想要对象做什么,一个可能的解决方案可能是:

import importlib
import os

for file in os.listdir("alpha"):
    if file.endswith(".py") and not file.startswith("_") and not file.startswith("Base"):
         class_name = os.path.splitext(file)[0] 
         module_name = "alpha" + '.' + class_name
         loaded_module = importlib.import_module(module_name)
         loaded_class = getattr(loaded_module, class_name)
         class_instance = loaded_class()

使用*导入所有内容并不是一个好习惯,所以如果你的文件只有一个类,那么导入这个类是“更干净”(class_name就是你的情况)

© www.soinside.com 2019 - 2024. All rights reserved.