你能像在 C#/Java 中一样将 python 项目逻辑地分成单独的文件/类吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2106271/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 23:48:15  来源:igfitidea点击:

Can you separate python projects logically into separate files/classes like in C#/Java?

python

提问by Mark

I'm looking to develop a project in python and all of the python I have done is minor scripting with no regard to classes or structure. I haven't seen much about this, so is this how larger python projects are done?

我正在寻找在 python 中开发一个项目,我所做的所有 python 都是小脚本,不考虑类或结构。我还没有看到太多关于这个的内容,那么大型 python 项目是如何完成的?

Also, do things like "namespaces" and "projects" exist in this realm? As well as object oriented principles such as inheriting from other classes?

另外,这个领域中是否存在“命名空间”和“项目”之类的东西?以及从其他类继承等面向对象的原则?

回答by Bandi-T

Yes, you can, and you should! :)

是的,你可以,而且你应该!:)

Here is a nice introduction to Python Modules(including packages).

这是对Python 模块(包括包)的一个很好的介绍。



Correction: you probably should not put each single class into a separate file (like Java mandates and many C++ places do). The language is pretty lax about it as you can see in the linked tutorial, keep an open eye on other projects, use common sense, and do whatever makes sense to you (or whatever is being done in your team/project - unless it is very wrong).

更正:您可能不应该将每个单独的类放入一个单独的文件中(就像 Java 指令和许多 C++ 地方所做的那样)。正如您在链接的教程中看到的那样,该语言对此非常松散,请密切关注其他项目,使用常识,并做任何对您有意义的事情(或您的团队/项目中正在做的任何事情 - 除非它是大错特错)。

回答by Jesse Kempf

You can put code (classes, function defs, etc) into python modules (individual source files), which are then imported with import. Typically like functionality (like in the Python standard library) is contained within a single module.

您可以将代码(类、函数定义等)放入 python 模块(单独的源文件)中,然后使用import. 通常类似的功能(比如在 Python 标准库中)包含在单个模块中。

回答by Reed Copsey

Yes.

是的。

You can put python classesinto separate files, use namespaces for scoping, then place this into Moduleswhich can be loaded from other scripts.

您可以将python 类放入单独的文件中,使用命名空间进行范围界定,然后将其放入可以从其他脚本加载的模块中。

回答by OscarRyz

You can do that, but usually they are arranged a bit different.

您可以这样做,但通常它们的排列方式略有不同。

You can take a look to the source code of one python application.

您可以查看一个 Python 应用程序的源代码。

Here's one: "JaikuEngine" which powers the website http://www.jaiku.com/

这是一个:“ JaikuEngine”,它为网站提供支持http://www.jaiku.com/