w00*_*00d 1 python import design-patterns class
我有一个使用MVC模式的项目.
在文件夹"models"中我有很多类,每个类现在都有自己的文件.但我觉得这样不方便,因为每次我需要使用一个类,我必须单独导入它.例如,我的应用程序源代码中有很多以下内容:
from models.classX import classX
from models.classY import classY
Run Code Online (Sandbox Code Playgroud)
如果我想一次导入的一切,像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
...
Run Code Online (Sandbox Code Playgroud)
然后在你的代码中你可以写:
import my.package.models.all as models # or from my.package.models.all import *
Run Code Online (Sandbox Code Playgroud)
并继续使用models.classX
,models.classY
等等.
归档时间: |
|
查看次数: |
717 次 |
最近记录: |