合理化Python中的包结构
我正在开发一个具有以下结构的 python 库
/application
/lib
__init__.py
/models
__init__.py
model1.py
model2.py
model3.py
在每个 model%.py 文件中都有一个名为 Model% 的相应类。我喜欢将这些类保留在自己的文件中,但这意味着在我的应用程序中我需要从模型包中导入类,就像这样
from models.model1 import Model1
from models.model2 import Model2
from models.model3 import Model3
有没有办法做到这一点?
from models import Model1, Model2, Model3
感觉更直观,更像我正在做的事情。我有一个名为 models 的包,我希望它包含这些类,但我仍然希望每个类都有自己的文件,这样我就可以通过简单地添加文件来添加新模型。
以前我把它放在我的 /application/lib/models/_init_py 文件中
from model1 import Model1
from model2 import Model2
from model3 import Model3
但我知道这是导入所有类,即使我只需要其中一个类
I am developing a python library with the following structure
/application
/lib
__init__.py
/models
__init__.py
model1.py
model2.py
model3.py
In each model%.py file there is a corresponding class named Model%. I like to keep these classes in their own files but it means that in my application I need to import classes from the models package like so
from models.model1 import Model1
from models.model2 import Model2
from models.model3 import Model3
Is there some way to do this instead?
from models import Model1, Model2, Model3
It feels more intuitive and more like what I am doing. I have a package called models and I want it to contain these classes but I still want each class to have its own file so I can add new models by simply adding a file.
Previously I put this in my /application/lib/models/_init_py file
from model1 import Model1
from model2 import Model2
from model3 import Model3
But I understood this was importing all the classes even when I only need one of them
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您的最终解决方案是正确的。如果加载太多类会导致严重的性能问题,那么您应该只担心加载太多类,对此我非常怀疑。
Your final solution is correct. You should only worry about loading too many classes if it is causing serious performance issues, which I highly doubt.
一种方法是在模型目录中创建一个导入类的文件,然后从该文件导入。例如,您可以创建一个名为 api.py 的文件,其中包含
然后您可以像这样导入模型
One way is to create a file in your models directory that imports your classes, then import from that file. For example, you could create a file called
api.py
that containsThen you could import the models like this
为每个模块创建单独的包。将
model1.py
放入model1
包中。在model1
包的__init__.py
文件中,然后放置,您将能够
从您的应用程序执行此操作。
Create separate package for each module. Put
model1.py
intomodel1
package. In__init__.py
file ofmodel1
package, putthen, you will be able to do
from your application.