Python 中的模块和包有什么区别?
Python 中的模块和包有什么区别?
另请参阅:“包”和“模块”之间有什么区别?(对于其他语言)
What's the difference between a module and package in Python?
See also: What's the difference between "package" and "module"? (for other languages)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(10)
模块:模块是一个简单的 Python 文件,其扩展名为 (
.py
),其中包含函数和全局变量的集合。它是一个可执行文件,Python 中的 Package 概念用于排列所有模块。示例:将代码保存在名为 demo (
module.py
) 的文件中。导入演示模块 module 并使用其中的 myModule1 函数。
解决方案:
包: 包是包含模块集合的基本目录。该目录包含 Python 模块以及解释器用来将其识别为包的 (
__init .py__
) 文件。包只不过是一个命名空间。包内还有子包。例如:
学生(套餐)
|
__init__.py
(构造函数)|
details.py
(模块)|
marks.py
(模块)|
collegeDetails.py
(模块)|
demo_module.py
(模块)包是组织成目录以形成包目录的一组模块。
Module: A module is a simple Python file with a (
.py
) extension that contains collections of functions and global variables. It is an executable file, and the notion of Package in Python is used to arrange all of the modules.For an Example: Save the code in a file called demo (
module.py
).Import the demo module module and use the myModule1 function within it.
Solution:
Package: A package is a basic directory that contains a collection of modules. This directory contains Python modules as well as a (
__init .py__
) file that the interpreter uses to recognize it as a Package. The package is nothing more than a namespace. Within the package, there are sub-packages.For an Example:
Student (Package)
|
__init__.py
(Constructor)|
details.py
(Module)|
marks.py
(Module)|
collegeDetails.py
(Module)|
demo_module.py
(Module)A package is a set of modules organized into directories to form a package directory.
我阅读了对此问题的不同答案。该问题已完全涵盖。但在我看来,加分或许也不是一个坏主意。如果我们检查不同模块的 __package__ 值,我们会得到以下结果。它们都是模块类型,但其中一些未定义包。检查__package__中的“随机”和“数学”。
因此,如果我们按如下方式定义一个文件夹:
这就是我们如何看到 __package__输出:
I read the different answers given to this question. The issue is fully covered. But it seems to me that making an extra point may not be a bad idea. If we examine the value of __package__ for different modules, we reach the following result. All of them are module types but for some of them the package is not defined. Check __package__ for "random" and "math".
So if we define a folder as follows:
This is how we can see the __package__ output:
下面简单介绍一下文档在 module 和 包:
模块是一个文件或包(文件夹)。
包是可以有多个模块(文件和包(文件夹))的模块。
就是文档在 模块 中实际所说的内容:
就是文档在 package 中实际所说的内容:
最后,您可以查看我的回答解释如何创建模块(文件和包),你可以看到 我的回答解释如何创建,上传并安装 TestPyPI 和 PyPI
Simply saying below about what the doc says in module and package:
A module is a file or package(folder).
A package is the module which can have multiple modules(files and packages(folders)).
And, this is what the doc actually says below in module:
And, this is what the doc actually says below in package:
Lastly, you can see my answer explaining how to create modules(files and packages) and you can see my answer explaining how to create, upload and install a package for TestPyPI and PyPI
我知道,现在已经太晚了,但是对于某些人来说,一个简单的答案就足够了:
模块是一个文件,
包是一个文件夹。
I know, it's too late, but a simple answer which would be sufficient for some is:
a module is a file,
a package is a folder.
没有
.py
扩展名。单个Python文件,包是Python模块的目录
包含一个附加的 __init__.py 文件,以区分包
来自恰好包含一堆 Python 的目录
脚本。包可以嵌套到任意深度,前提是
相应的目录包含自己的
__init__.py
文件。模块和包之间的区别似乎只存在于文件系统级别。当您导入模块或包时,Python创建的相应对象始终是
模块
类型。但请注意,当您导入包时,只有该包的__init__.py
文件中的变量/函数/类是直接可见的, 不是子包或模块。示例
作为一个示例,请考虑 Python 标准库中的
xml
包:其xml
目录包含一个__init__.py
文件和四个子目录;子目录etree
包含一个__init__.py
文件以及一个ElementTree.py
文件。看看当您尝试以交互方式导入包/模块时会发生什么:
注意
在 Python 中还有 内置模块,例如用C编写的
sys
,但我认为您并不打算考虑问题中的那些模块。without the
.py
extension.single Python file, a package is a directory of Python modules
containing an additional
__init__.py
file, to distinguish a packagefrom a directory that just happens to contain a bunch of Python
scripts. Packages can be nested to any depth, provided that the
corresponding directories contain their own
__init__.py
file.The distinction between module and package seems to hold just at the file system level. When you import a module or a package, the corresponding object created by Python is always of type
module
. Note, however, when you import a package, only variables/functions/classes in the__init__.py
file of that package are directly visible, not sub-packages or modules.Example
As an example, consider the
xml
package in the Python standard library: itsxml
directory contains an__init__.py
file and four sub-directories; the sub-directoryetree
contains an__init__.py
file and, among others, anElementTree.py
file.See what happens when you try to interactively import package/modules:
NOTE
In Python there also are built-in modules, such as
sys
, that are written in C, but I don't think you meant to consider those in your question.模块是在一次导入下导入并使用的单个文件(或多个文件)。
例如,
包是提供包层次结构的目录中的模块集合。
模块文档
包介绍
A module is a single file (or files) that are imported under one import and used.
e.g.
A package is a collection of modules in directories that give a package hierarchy.
Documentation for modules
Introduction to packages
首先,请记住,按照其精确定义,模块是 Python 解释器内存中的一个对象,通常是通过从磁盘读取一个或多个文件来创建的。虽然我们可能会非正式地将诸如
a/b/c.py
之类的磁盘文件称为“模块”,但在与其他几个来源(例如>sys.path
) 来创建模块对象。(请注意,例如,可以从同一个文件加载两个具有不同名称的模块,具体取决于 sys.path 和其他设置。这正是使用 python -m my.path 时发生的情况。 module 后跟解释器中的
import my.module
;将有两个模块对象,__main__
和my.module
,两者都是从磁盘上的同一文件创建的,my/module.py
。)包是可能具有子模块(包括子包)的模块。并非所有模块都能做到这一点。例如,创建一个小型模块层次结构:
确保
a
下没有其他文件。启动Python 3.4或更高版本的解释器(例如,使用python3 -i
)并检查以下语句的结果:模块
a
和ab
是包(事实上,某种称为“命名空间包”的包,尽管我们在这里不担心这一点)。但是,模块abc
不是一个包。我们可以通过向上面的目录结构添加另一个文件a/b.py
并启动一个新的解释器来演示这一点:Python 确保在加载子模块之前加载所有父模块。上面发现
a/
是一个目录,因此创建了一个命名空间包a
,并且a/b.py
是一个Python源它加载并使用该文件来创建(非包)模块ab
。此时,您不能拥有模块abc
,因为ab
不是包,因此不能拥有子模块。您还可以在这里看到包模块
a
有一个__path__
属性(包必须有这个),但非包模块ab
没有。First, keep in mind that, in its precise definition, a module is an object in the memory of a Python interpreter, often created by reading one or more files from disk. While we may informally call a disk file such as
a/b/c.py
a "module," it doesn't actually become one until it's combined with information from several other sources (such assys.path
) to create the module object.(Note, for example, that two modules with different names can be loaded from the same file, depending on
sys.path
and other settings. This is exactly what happens withpython -m my.module
followed by animport my.module
in the interpreter; there will be two module objects,__main__
andmy.module
, both created from the same file on disk,my/module.py
.)A package is a module that may have submodules (including subpackages). Not all modules can do this. As an example, create a small module hierarchy:
Ensure that there are no other files under
a
. Start a Python 3.4 or later interpreter (e.g., withpython3 -i
) and examine the results of the following statements:Modules
a
anda.b
are packages (in fact, a certain kind of package called a "namespace package," though we wont' worry about that here). However, modulea.b.c
is not a package. We can demonstrate this by adding another file,a/b.py
to the directory structure above and starting a fresh interpreter:Python ensures that all parent modules are loaded before a child module is loaded. Above it finds that
a/
is a directory, and so creates a namespace packagea
, and thata/b.py
is a Python source file which it loads and uses to create a (non-package) modulea.b
. At this point you cannot have a modulea.b.c
becausea.b
is not a package, and thus cannot have submodules.You can also see here that the package module
a
has a__path__
attribute (packages must have this) but the non-package modulea.b
does not.来自 Python 术语表:
名称中带有破折号的 Python 文件(例如
my-file.py
)不能被使用简单的import
语句导入。从代码角度来看,import my-file
与import my-file
相同,都会引发异常。此类文件更适合描述为脚本,而可导入文件则为模块。From the Python glossary:
Python files with a dash in the name, like
my-file.py
, cannot be imported with a simpleimport
statement. Code-wise,import my-file
is the same asimport my - file
which will raise an exception. Such files are better characterized as scripts whereas importable files are modules.这里的其他答案可能仍然有点模糊,所以我发布了一个希望更清晰的答案。值得注意的是,问题的标题首先也有点误导,我认为更好的标题是:“与常规模块相比,包模块有什么特别之处?”。
TL;DR - 简短回答:
包也是模块,但是它们是模块的一种特殊类型。特殊是指1.它们是“目录”,2.它们可能包含特殊文件,例如
__init__.py
和__main__.py
。为了更好地理解 - 更长的答案:
重点是,包是一种特殊类型的模块,因此我们需要首先了解一般模块,然后再了解包的特殊之处模块也有意义。 (注意:我有时会在这个答案中将“包模块”称为“包”,反之亦然)
因此,让我们首先讨论一下一般的模块,因为它不会那么模糊/更容易理解。 我们对模块基本上做了两件事,要么将它们导入其他模块,要么直接通过 Python 执行它们。
导入模块有一个明显的目标,即访问该模块内部的内容。
然而,执行模块通常会追求以下两个目标之一:
让我们通过一些示例来更好地理解所有这些:
导入模块:
执行模块
目标 1,将模块作为主模块执行:
让我们假设
foo.上面示例中的 py
模块是启动我们的程序的主模块。我们可以通过在终端中输入以下命令来运行它:python3 foo.py # <--执行主模块
然后它将启动我们的程序。目标 2,单独尝试模块的功能:
假设我们想要尝试上例中
bar.py
模块中的函数talk
,而不运行整个模块程序,即不调用模块foo.py
。为此,我们必须稍微更改bar.py
:现在在终端中运行以下命令:
python3 bar.py # <-- 尝试隔离模块的功能< /code> 然后它会打印
bar
。现在我们知道了一般可以用模块做什么,让我们回到主要问题:
与常规模块相比,包模块有什么特别之处?
1. Python 中的常规模块只是“文件”,而包模块则是“目录”。
2. 常规模块可以“导入”并且可以“执行”(如上面的示例所示),包模块也可以“导入”并且可以“执行”,但是,您可能会抱怨:“但我们不能直接在目录中编写代码!代码只能在文件中编写!”,这确实是一个很好的抱怨,因为它引导我们了解了关于包模块的第二个特殊之处。包模块的代码编写在其目录内的文件中,并且这些文件的名称也由Python保留。如果你想“导入”一个包模块,你必须将其代码放在其目录中的
__init__.py
文件中,如果你想“执行”一个包模块,你'必须将其执行代码放在其目录中的 __main__.py 文件中。这是上述解释的最后一个示例:
The other answers here may still be a bit vague, so I'm posting a hopefully clearer answer. It's important to note that the title of the question is also a bit misleading in the first place, and a better title in my opinion would be: "What is special about package modules compared to regular modules?".
TL;DR - Short Answer:
Packages are modules too, they are however, a special type of them. Special in the sense that 1. they are "directories" and 2. they may contain special files such as
__init__.py
and__main__.py
.To Better Understand - Longer Answer:
The point is, packages are a special type of modules, so we need to understand modules in general first, and then what's special about the package modules will make sense too. (Notice: I'll sometimes refer to "package modules" in this answer as just "packages", and vice versa)
So let's talk about modules in general first, as it would be less vague / easier to understand. There are basically two things that we do with modules, we either import them in other modules, or execute them directly by Python.
Importing a module has a single obvious goal, accessing what that module has inside.
Executing a module however, usually pursues one of these two goals:
Let's make more sense of all these through some examples:
Importing modules:
Executing Modules
Goal 1, executing a module as a main module:
Let's assume that the
foo.py
module in the example above, is a main module that starts our program. We can run it by typing this command in the terminal:python3 foo.py # <-- executing a main module
and then it will start our program.Goal 2, trying functionalities of a module in isolation:
Let's assume that we want to try the function
talk
in thebar.py
module in the example above, without running our whole program, i.e., without calling the modulefoo.py
. For that, we'll have to slightly change thebar.py
:Now run this command in the terminal:
python3 bar.py # <-- trying functionalities of a module in isolation
and then it will printbar
.Now that we know what we can do with modules in general, let's return to the main question:
What is special about package modules compared to regular modules?
1. Regular modules in Python are just "files", package modules are however, "directories".
2. Regular modules can be "imported" and can be "executed" (as shown in the examples above), package modules ALSO can be "imported" and can be "executed", HOWEVER, you may rightly complain: "but we can't directly write code in directories! Code is written in files only!", and that's indeed a very good complaint, as it leads us to the second special thing about package modules. The code for a package module is written in files inside its directory, and the names of these files are also reserved by Python. If you want to "import" a package module, you'll have to put its code in an
__init__.py
file in its directory, and if you want to "execute" a package module, you'll have to put the execution code of it in a__main__.py
file in its directory.And here's the final example for the explanation above:
迟到的答案,还有另一个定义:
因此,从物理上来说,包是一个分发单元,它提供一个或多个模块。
A late answer, yet another definition:
So physically a package is a distribution unit, which provides one or more modules.