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

2024-03-29 11:34:45 发布

您现在位置:Python中文网/ 问答频道 /正文

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

另请参见:What's the difference between "package" and "module"(其他语言)


Tags: 模块andthe语言packagebetweenwhatmodule
3条回答

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文件(如my-file.py)不能用简单的import语句导入。代码方面,import my-fileimport my - file相同,后者将引发异常。这样的文件更好地描述为脚本而可导入的文件是模块

模块是在一个导入下导入并使用的单个文件。 e、 g

import my_module

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

from my_package.timing.danger.internets import function_of_love

Documentation for modules

Introduction to packages

任何Python文件都是一个module,其名称是文件的基本名称,没有.py扩展名。package是Python模块的集合:当模块是一个Python文件时,包是包含一个附加的__init__.py文件的Python模块的目录,用于区分包与刚好包含一堆Python脚本的目录。如果相应的目录包含自己的__init__.py文件,则包可以嵌套到任何深度。

模块和包之间的区别似乎只存在于文件系统级别。当您导入模块或包时,Python创建的相应对象总是module类型。但是,请注意,导入包时,只有该包的__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,但是我不认为您打算考虑这些问题。

相关问题 更多 >