Python 中的模块和包有什么区别?

发布于 2024-12-12 10:37:21 字数 170 浏览 0 评论 0原文

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 技术交流群。

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

发布评论

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

评论(10

余厌 2024-12-19 10:37:22

模块:模块是一个简单的 Python 文件,其扩展名为 (.py),其中包含函数和全局变量的集合。它是一个可执行文件,Python 中的 Package 概念用于排列所有模块。

示例:将代码保存在名为 demo (module.py) 的文件中。

def myModule1(name):
    print("My Module name is: "+ name)

导入演示模块 module 并使用其中的 myModule1 函数。

import demo_module
  
demo_module.myModule1("Math")

解决方案:

我的模块名称是:数学

包: 包是包含模块集合的基本目录。该目录包含 Python 模块以及解释器用来将其识别为包的 (__init .py__) 文件。包只不过是一个命名空间。包内还有子包。

例如:

学生(套餐)

| __init__.py(构造函数)

| details.py(模块)

| marks.py(模块)

| collegeDetails.py(模块)

| demo_module.py (模块)

包是组织成目录以形成包目录的一组模块。

from Student import details, collegeDetails, demo_module

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).

def myModule1(name):
    print("My Module name is: "+ name)

Import the demo module module and use the myModule1 function within it.

import demo_module
  
demo_module.myModule1("Math")

Solution:

My Module name is: Math

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.

from Student import details, collegeDetails, demo_module
悲念泪 2024-12-19 10:37:22

我阅读了对此问题的不同答案。该问题已完全涵盖。但在我看来,加分或许也不是一个坏主意。如果我们检查不同模块的 __package__ 值,我们会得到以下结果。它们都是模块类型,但其中一些未定义包。检查__package__中的“随机”和“数学”。

import cv2
import math
import random
import tkinter as tk

print('cv2:',type(cv2))             # <class 'module'>
print('cv2:',cv2)                   # <module 'cv2.cv2' from 'PATH'>
print('cv2:',cv2.__package__)       # cv2

print('random:',type(random))       # <class 'module'>
print('random:',random)             # <module 'random' from 'PATH'>
print('random:',random.__package__) # [EMPTY]

print('tk:',type(tk))               # <class 'module'>
print('tk:',tk)                     # <module 'tkinter' from 'PATH'>
print('tk:',tk.__package__)         # tkinter

print('math:',type(math))           # <class 'module'>
print('math:',math)                 # <module 'math' (built-in)>
print('math:',math.__package__)     # [EMPTY]

因此,如果我们按如下方式定义一个文件夹:

在此处输入图像描述

这就是我们如何看到 __package__输出:

import myfolder
import myfolder.script1 as s1
import myfolder.script2 as s2
import myfolder.mySubfolder.script3 as s3

print(type(s1)) # <class 'module'>
print(type(s2)) # <class 'module'>
print(type(s3)) # <class 'module'>

print(s1.__package__) # myfolder
print(s2.__package__) # myfolder
print(s3.__package__) # myfolder.mySubfolder

print(myfolder)                     # <module 'myfolder' (namespace)>
print(myfolder.mySubfolder)         # <module 'myfolder.mySubfolder' (namespace)>
print(myfolder.mySubfolder.script3) # <module 'myfolder.mySubfolder.script3' from 'PATH'>

print(myfolder.__package__)                     # myfolder        
print(myfolder.mySubfolder.__package__)         # myfolder.mySubfolder
print(myfolder.mySubfolder.script3.__package__) # myfolder.mySubfolder

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".

import cv2
import math
import random
import tkinter as tk

print('cv2:',type(cv2))             # <class 'module'>
print('cv2:',cv2)                   # <module 'cv2.cv2' from 'PATH'>
print('cv2:',cv2.__package__)       # cv2

print('random:',type(random))       # <class 'module'>
print('random:',random)             # <module 'random' from 'PATH'>
print('random:',random.__package__) # [EMPTY]

print('tk:',type(tk))               # <class 'module'>
print('tk:',tk)                     # <module 'tkinter' from 'PATH'>
print('tk:',tk.__package__)         # tkinter

print('math:',type(math))           # <class 'module'>
print('math:',math)                 # <module 'math' (built-in)>
print('math:',math.__package__)     # [EMPTY]

So if we define a folder as follows:

enter image description here

This is how we can see the __package__ output:

import myfolder
import myfolder.script1 as s1
import myfolder.script2 as s2
import myfolder.mySubfolder.script3 as s3

print(type(s1)) # <class 'module'>
print(type(s2)) # <class 'module'>
print(type(s3)) # <class 'module'>

print(s1.__package__) # myfolder
print(s2.__package__) # myfolder
print(s3.__package__) # myfolder.mySubfolder

print(myfolder)                     # <module 'myfolder' (namespace)>
print(myfolder.mySubfolder)         # <module 'myfolder.mySubfolder' (namespace)>
print(myfolder.mySubfolder.script3) # <module 'myfolder.mySubfolder.script3' from 'PATH'>

print(myfolder.__package__)                     # myfolder        
print(myfolder.mySubfolder.__package__)         # myfolder.mySubfolder
print(myfolder.mySubfolder.script3.__package__) # myfolder.mySubfolder
○愚か者の日 2024-12-19 10:37:22

下面简单介绍一下文档在 module

  • 模块是一个文件或包(文件夹)。

  • 是可以有多个模块(文件和包(文件夹))的模块。

就是文档在 模块 中实际所说的内容:

  • 而且,这 对象作为Python代码的组织单元。模块有一个包含任意 Python 对象的命名空间。模块通过导入过程加载到 Python 中。

就是文档在 package 中实际所说的内容:

  • 而且,这 Python 模块可以包含子模块或递归子包。从技术上讲,包是一个带有 path 属性的 Python 模块。

最后,您可以查看我的回答解释如何创建模块(文件和包),你可以看到 我的回答解释如何创建,上传并安装 TestPyPIPyPI

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:

  • An object that serves as an organizational unit of Python code. Modules have a namespace containing arbitrary Python objects. Modules are loaded into Python by the process of importing.

And, this is what the doc actually says below in package:

  • A Python module which can contain submodules or recursively, subpackages. Technically, a package is a Python module with a path attribute.

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

薄暮涼年 2024-12-19 10:37:22

我知道,现在已经太晚了,但是对于某些人来说,一个简单的答案就足够了:

模块是一个文件,

包是一个文件夹。

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.

友谊不毕业 2024-12-19 10:37:21
  • 任何Python文件都是一个模块,其名称是文件的基本名称
    没有 .py 扩展名。
  • 是一个集合:模块是
    单个Python文件,包是Python模块的目录
    包含一个附加的 __init__.py 文件,以区分包
    来自恰好包含一堆 Python 的目录
    脚本。包可以嵌套到任意深度,前提是
    相应的目录包含自己的__init__.py文件。

模块之间的区别似乎只存在于文件系统级别。当您导入模块时,Python创建的相应对象始终是模块类型。但请注意,当您导入时,只有该__init__.py文件中的变量/函数/类是直接可见的, 不是子包模块


示例

作为一个示例,请考虑 Python 标准库中的 xml 包:其 xml 目录包含一个 __init__.py 文件和四个子目录;子目录 etree 包含一个 __init__.py 文件以及一个 ElementTree.py 文件。

看看当您尝试以交互方式导入包/模块时会发生什么:

>>> import xml
>>> type(xml)
<type 'module'>
>>> xml.etree.ElementTree
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'etree'
>>>
>>>
>>> import xml.etree
>>> type(xml.etree)
<type 'module'>
>>> xml.etree.ElementTree
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'ElementTree'
>>>
>>>
>>> import xml.etree.ElementTree
>>> type(xml.etree.ElementTree)
<type 'module'>
>>> xml.etree.ElementTree.parse
<function parse at 0x00B135B0>

注意

在 Python 中还有 内置模块,例如用C编写的sys,但我认为您并不打算考虑问题中的那些模块。

  • Any Python file is a module, its name being the file's base name
    without the .py extension.
  • A package is a collection of Python modules: while a module is a
    single Python file, a package is a directory of Python modules
    containing an additional __init__.py file, to distinguish a package
    from 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: its xml directory contains an __init__.py file and four sub-directories; the sub-directory etree contains an __init__.py file and, among others, an ElementTree.py file.

See what happens when you try to interactively import package/modules:

>>> import xml
>>> type(xml)
<type 'module'>
>>> xml.etree.ElementTree
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'etree'
>>>
>>>
>>> import xml.etree
>>> type(xml.etree)
<type 'module'>
>>> xml.etree.ElementTree
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'ElementTree'
>>>
>>>
>>> import xml.etree.ElementTree
>>> type(xml.etree.ElementTree)
<type 'module'>
>>> xml.etree.ElementTree.parse
<function parse at 0x00B135B0>

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.

永不分离 2024-12-19 10:37:21

模块是在一次导入下导入并使用的单个文件(或多个文件)。
例如,

import my_module

包是提供包层次结构的目录中的模块集合。

from my_package.timing.danger.internets import function_of_love

模块文档

包介绍

A module is a single file (or files) that are imported under one import and used.
e.g.

import my_module

A package is a collection of modules in directories that give a package hierarchy.

from my_package.timing.danger.internets import function_of_love

Documentation for modules

Introduction to packages

演出会有结束 2024-12-19 10:37:21

首先,请记住,按照其精确定义,模块是 Python 解释器内存中的一个对象,通常是通过从磁盘读取一个或多个文件来创建的。虽然我们可能会非正式地将诸如 a/b/c.py 之类的磁盘文件称为“模块”,但在与其他几个来源(例如 >sys.path) 来创建模块对象。

(请注意,例如,可以从同一个文件加载两个具有不同名称的模块,具体取决于 sys.path 和其他设置。这正是使用 python -m my.path 时发生的情况。 module 后跟解释器中的 import my.module;将有两个模块对象,__main__my.module,两者都是从磁盘上的同一文件创建的, my/module.py。)

是可能具有子模块(包括子包)的模块。并非所有模块都能做到这一点。例如,创建一个小型模块层次结构:

$ mkdir -p a/b
$ touch a/b/c.py

确保 a 下没有其他文件。启动Python 3.4或更高版本的解释器(例如,使用python3 -i)并检查以下语句的结果:

import a
a                ⇒ <module 'a' (namespace)>
a.b              ⇒ AttributeError: module 'a' has no attribute 'b'
import a.b.c
a.b              ⇒ <module 'a.b' (namespace)>
a.b.c            ⇒ <module 'a.b.c' from '/home/cjs/a/b/c.py'>

模块aab是包(事实上,某种称为“命名空间包”的包,尽管我们在这里不担心这一点)。但是,模块abc 不是一个包。我们可以通过向上面的目录结构添加另一个文件 a/b.py 并启动一个新的解释器来演示这一点:

import a.b.c
⇒ ImportError: No module named 'a.b.c'; 'a.b' is not a package
import a.b
a                ⇒ <module 'a' (namespace)>
a.__path__       ⇒ _NamespacePath(['/.../a'])
a.b              ⇒ <module 'a.b' from '/home/cjs/tmp/a/b.py'>
a.b.__path__     ⇒ AttributeError: 'module' object has no attribute '__path__'

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 as sys.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 with python -m my.module followed by an import my.module in the interpreter; there will be two module objects, __main__ and my.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:

$ mkdir -p a/b
$ touch a/b/c.py

Ensure that there are no other files under a. Start a Python 3.4 or later interpreter (e.g., with python3 -i) and examine the results of the following statements:

import a
a                ⇒ <module 'a' (namespace)>
a.b              ⇒ AttributeError: module 'a' has no attribute 'b'
import a.b.c
a.b              ⇒ <module 'a.b' (namespace)>
a.b.c            ⇒ <module 'a.b.c' from '/home/cjs/a/b/c.py'>

Modules a and a.b are packages (in fact, a certain kind of package called a "namespace package," though we wont' worry about that here). However, module a.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:

import a.b.c
⇒ ImportError: No module named 'a.b.c'; 'a.b' is not a package
import a.b
a                ⇒ <module 'a' (namespace)>
a.__path__       ⇒ _NamespacePath(['/.../a'])
a.b              ⇒ <module 'a.b' from '/home/cjs/tmp/a/b.py'>
a.b.__path__     ⇒ AttributeError: 'module' object has no attribute '__path__'

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 package a, and that a/b.py is a Python source file which it loads and uses to create a (non-package) module a.b. At this point you cannot have a module a.b.c because a.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 module a.b does not.

又怨 2024-12-19 10:37:21

来自 Python 术语表

重要的是要记住,所有包都是模块,但并非所有模块都是包。或者换句话说,包只是一种特殊的模块。具体来说,任何包含 __path__ 属性的模块都被视为包。

名称中带有破折号的 Python 文件(例如 my-file.py)不能被使用简单的 import 语句导入。从代码角度来看,import my-fileimport my-file 相同,都会引发异常。此类文件更适合描述为脚本,而可导入文件则为模块

From the Python glossary:

It’s important to keep in mind that all packages are modules, but not all modules are packages. Or put another way, packages are just a special kind of module. Specifically, any module that contains a __path__ attribute is considered a package.

Python files with a dash in the name, like my-file.py, cannot be imported with a simple import statement. Code-wise, import my-file is the same as import my - file which will raise an exception. Such files are better characterized as scripts whereas importable files are modules.

夜血缘 2024-12-19 10:37:21

这里的其他答案可能仍然有点模糊,所以我发布了一个希望更清晰的答案。值得注意的是,问题的标题首先也有点误导,我认为更好的标题是:与常规模块相比,包模块有什么特别之处?”

TL;DR - 简短回答:

包也是模块,但是它们是模块的一种特殊类型。特殊是指1.它们是“目录”,2.它们可能包含特殊文件,例如__init__.py__main__.py

为了更好地理解 - 更长的答案:

重点是,包是一种特殊类型的模块,因此我们需要首先了解一般模块,然后再了解包的特殊之处模块也有意义。 (注意:我有时会在这个答案中将“包模块”称为“包”,反之亦然)

因此,让我们首先讨论一下一般的模块,因为它不会那么模糊/更容易理解。 我们对模块基本上做了两件事,要么将它们导入其他模块,要么直接通过 Python 执行它们。

导入模块有一个明显的目标,即访问该模块内部的内容。

然而,执行模块通常会追求以下两个目标之一:

  1. 该模块是主模块,执行它将启动我们的程序(或其子程序之一)。
  2. 我们希望单独尝试该模块的功能,即无需先导入它。

让我们通过一些示例来更好地理解所有这些:

导入模块:

# bar.py

def talk():
    print("bar")
# foo.py

import bar # <-- importing module "bar"

bar.talk() # <-- prints "bar"

执行模块

目标 1,将模块作为主模块执行:

让我们假设 foo.上面示例中的 py 模块是启动我们的程序的主模块。我们可以通过在终端中输入以下命令来运行它:python3 foo.py # <--执行主模块然后它将启动我们的程序。

目标 2,单独尝试模块的功能:

假设我们想要尝试上例中 bar.py 模块中的函数 talk,而不运行整个模块程序,即不调用模块foo.py。为此,我们必须稍微更改 bar.py

# bar.py

def talk():
    print("bar")

if __name__ == '__main__':
    talk()

现在在终端中运行以下命令:python3 bar.py # <-- 尝试隔离模块的功能< /code> 然后它会打印 bar

现在我们知道了一般可以用模块做什么,让我们回到主要问题:

与常规模块相比,包模块有什么特别之处?

1. Python 中的常规模块只是“文件”,而包模块则是“目录”。

2. 常规模块可以“导入”并且可以“执行”(如上面的示例所示),包模块也可以“导入”并且可以“执行”,但是,您可能会抱怨:“但我们不能直接在目录中编写代码!代码只能在文件中编写!”,这确实是一个很好的抱怨,因为它引导我们了解了关于包模块的第二个特殊之处。包模块的代码编写在其目录内的文件中,并且这些文件的名称也由Python保留。如果你想“导入”一个包模块,你必须将其代码放在其目录中的 __init__.py 文件中,如果你想“执行”一个包模块,你'必须将其执行代码放在其目录中的 __main__.py 文件中。

这是上述解释的最后一个示例:

# hierarchy of files and folders:
.
├── bar_pack/
│   ├── __init__.py
│   ├── __main__.py
│   foo.py
# bar_pack/__init__.py

def talk():
    print("bar")
# bar_pack/__main__.py

import __init__

__init__.talk()
# foo.py

import bar_pack # <-- importing package module "bar_pack"

bar_pack.talk() # <-- prints "bar"
# Run this command in the terminal:
python3 bar_pack # <-- executing the package module "bar_pack", prints "bar"

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:

  1. That module is a main module and executing it will start our program (or one of its subprograms).
  2. We want to try the functionalities of that module in isolation, i.e., without having to import it first.

Let's make more sense of all these through some examples:

Importing modules:

# bar.py

def talk():
    print("bar")
# foo.py

import bar # <-- importing module "bar"

bar.talk() # <-- prints "bar"

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 the bar.py module in the example above, without running our whole program, i.e., without calling the module foo.py. For that, we'll have to slightly change the bar.py:

# bar.py

def talk():
    print("bar")

if __name__ == '__main__':
    talk()

Now run this command in the terminal: python3 bar.py # <-- trying functionalities of a module in isolation and then it will print bar.

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:

# hierarchy of files and folders:
.
├── bar_pack/
│   ├── __init__.py
│   ├── __main__.py
│   foo.py
# bar_pack/__init__.py

def talk():
    print("bar")
# bar_pack/__main__.py

import __init__

__init__.talk()
# foo.py

import bar_pack # <-- importing package module "bar_pack"

bar_pack.talk() # <-- prints "bar"
# Run this command in the terminal:
python3 bar_pack # <-- executing the package module "bar_pack", prints "bar"
自我难过 2024-12-19 10:37:21

迟到的答案,还有另一个定义:

一个包由一个导入的顶级实体表示,它可以
是一个独立的模块,或者 __init__.py 特殊模块作为
子目录结构中一组模块的顶级实体。

因此,从物理上来说,包是一个分发单元,它提供一个或多个模块。

A late answer, yet another definition:

A package is represented by an imported top-entity which could either
be a self-contained module, or the __init__.py special module as the
top-entity from a set of modules within a sub directory structure.

So physically a package is a distribution unit, which provides one or more modules.

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