简体   繁体   English

如何在项目中正确加载Python类?

[英]How can I properly load a Python class in my project?

My older structure is: 我的旧结构是:

在此处输入图片说明

In a file, I'm doing: 在一个文件中,我正在做:

from CodeModel import CodeModel

codemodel = CodeModel.CodeModel()

But that seems redundant. 但这似乎是多余的。 Is there a cleaner way to import CodeModel without having to do CodeModel.CodeModel() ? 是否有一种更清洁的方式导入CodeModel而无需执行CodeModel.CodeModel()

from CodeModel.CodeModel import CodeModel

but you should think of different packages&modules structure because it may indeed be redundant. 但您应该考虑不同的包和模块结构,因为它确实可能是多余的。

If you have multiple (but not really many) models, think of creating modules.py with CodeModel and other model classes. 如果你有多个(但不是真的很多)模型,认为创建与CodeModel和其他模型类modules.py的。 Simplify things if possible (adequatly to project's size). 尽可能简化事情(适当地取决于项目的大小)。

from models import CodeModel

seems better, doesn't it? 看起来更好,不是吗?

Another option would be 另一种选择是

from .CodeModel import CodeModel

inside __init__.py of CodeModel package, already mentioned in the comment by Patrick Haugh. Patrick Haugh的注释中已经提到了CodeModel包的__init__.py中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM