Python源文件组织

发布于 2024-10-07 14:39:54 字数 143 浏览 5 评论 0原文

我正在开始一个新的 Python 项目,并且希望尽可能严格地遵循标准约定。例如,我读过导入语句应该放在第一位。但我还没有找到任何约定,例如将所有函数定义放在所有类定义之前或之后。对于这样的事情有什么约定吗?或者每个人通常只是按照似乎有意义的顺序组织函数和类定义之类的东西?

I'm starting a new Python project, and want to follow standard conventions as closely as possible. I've read that import statements should come first, for example. But I haven't found any conventions for things like putting all function definitions before or after all class definitions. Are there any conventions for things like this? Or does everyone typically just organize things like function and class definitions in whatever order seems to make sense?

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

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

发布评论

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

评论(2

作业与我同在 2024-10-14 14:39:54

PEP8 是 Python 风格指南:http://www.python.org/dev/peps /pep-0008/

导入位于文件顶部,但允许方法级导入。

类和函数没有特定的顺序。使用有意义的东西。

PEP8 is the Python style guide: http://www.python.org/dev/peps/pep-0008/

Imports come at the top of the file, though method-level imports are allowed.

There's no specific ordering to classes and functions. Use what makes sense.

痴情换悲伤 2024-10-14 14:39:54

不,没有函数和类的组织约定。但是,有一些基本准则可以使您的源代码流程更好,并且对读者更有意义:

  • 文档。无论你做什么,都要确保类和函数的使用(在某些情况下,实现)是用简单的英语描述的)
  • 将相似的东西分组在一起。执行相似功能的两个函数?把它们放在一起。
  • 使用常识。如果一个类扩展另一个类,则基类应该放在第一位。如果函数采用您定义的类的实例,请确保类定义位于第一位。

有关如何完成此操作的示例,只需查看 Python 标准库即可。某些模块的源文件应该能让您了解 Python 中源代码的组织方式。

No, there's no convention for organization of functions and classes. However, there are some basic guidelines that will make your source flow better and make more sense to readers:

  • Document. Whatever you do, make sure that the uses (and in some cases, implementation) of classes and functions is described in plain english)
  • Group together things that are alike. Two functions that perform similar functions? Put them together.
  • Use common sense. If a class extends another, the base class should come first. If a function takes an instance of a class you defined, make sure the class definition comes first.

For examples on how this is done, look no further than the Python standard library. The source files from some of the modules should give you an idea how source is organized in Python.

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