Skip to main content
 首页 » 编程设计

Python 在单独的文件中管理类

2025年05月04日23lvdongjie

我有一个使用 MVC 模式的项目。

在“模型”文件夹中我有很多类,每个类现在都有自己的文件。但是感觉不太方便,因为每次需要用到一个类都得单独导入。例如。我的应用程序源中有许多以下内容:

from models.classX import classX 
from models.classY import classY 

如果我想一次导入所有内容,比如 from models import * 我发现我可以将所有类型的 import 放在 models/__init__ 中。 py。但这是 pythonic 的方式吗?约定是什么?

请您参考如下方法:

Python 不是 java;请避免每个类一个文件的模式。如果您无法更改它,您可以从 models 包的子模块中导入所有这些:

# all.py: convenient import of all the needed classes 
from models.classX import classX 
from models.classY import classY 
... 

然后在你的代码中你可以这样写:

import my.package.models.all as models  # or from my.package.models.all import * 

然后继续使用 models.classX、models.classY 等