如何组织Python源代码文件?

发布于 2024-08-21 13:16:25 字数 1431 浏览 3 评论 0原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

白云不回头 2024-08-28 13:16:25

将空的 __init__.py 文件放入 Models 目录中。

然后,在您的应用程序中;大概上一层,您可以像这样引用 Models 目录中的模块:

import Models

并对其执行如下操作:

Models.my_model.MyClassName

您还可以使用 from 关键字,如下所示:

from Models import my_model

并像这样引用:

my_model.MyClassName

如果您只需要一个模块中的方法,您也可以这样做:

from Models.my_model import my_method_name
my_method_name()

指向文档的强制链接

Put an empty __init__.py file in the Models directory.

Then, in your app; presumably one level up, you reference modules in the Models directory like this:

import Models

and do something with it like this:

Models.my_model.MyClassName

You can also use the from keyword like this:

from Models import my_model

and reference like this:

my_model.MyClassName

If you only need one method from a module, you could also do this:

from Models.my_model import my_method_name
my_method_name()

Obligatory link to the documentation.

初与友歌 2024-08-28 13:16:25

为了回应您对 Adam 的回答的评论,关于 10 个类有 10 个导入,首先不要忘记,Python 中的每个模块不需要一个类。模块应该按功能进行组织,因此您可以将相关的类分组到单个文件中(如果有意义的话)。

如果您仍然想让所有类一次性导入,您可以使用 from submodule import Class 语法将它们全部导入到 __init__.py 文件本身中,然后只需导入包含模块 - import mainmodule 并引用 mainmodule.Class1 等,甚至使用 from mainmodule import Class1, Class2, Class3 导入类直接添加到您的命名空间中并直接引用它们。

In response to your comment to Adam's answer, regarding having 10 imports for 10 classes, firstly don't forget that there's no need to have one class per module in Python. Modules should be organised by functionality, so you can group related classes in a single file if that makes sense.

If you still wanted to make all the classes importable in one go, you could import them all in the __init__.py file itself using the from submodule import Class syntax, then just import the containing module - import mainmodule and refer to mainmodule.Class1 etc, or even use from mainmodule import Class1, Class2, Class3 to import the classes directly into your namespace and refer to them directly.

π浅易 2024-08-28 13:16:25

Adam Bernier 对包的工作原理提供了很好的技术描述。 http://jcalderone.livejournal.com/ 中详细描述了如何安排和交付项目39794.html

Adam Bernier provides a good technical description of how packages work. A great description of how to arrange and ship a project is described in http://jcalderone.livejournal.com/39794.html

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文