Python 中的模块和包有什么区别?
也可以看看:“包”和“模块”有什么区别? https://stackoverflow.com/questions/3680883/whats-the-difference-between-package-and-module(对于其他语言)
- 任何Python文件都是module http://docs.python.org/tutorial/modules.html,其名称是文件的基本名称
没有
.py
扩大。
- A package http://docs.python.org/tutorial/modules.html#packages is a 收藏Python 模块的组成:模块是
单个Python文件,包是Python模块的目录
包含一个额外的
__init__.py
文件,区分包
来自恰好包含一堆 Python 的目录
脚本。包可以嵌套到任意深度,前提是
相应的目录包含自己的__init__.py
file.
之间的区别module and package似乎只适用于文件系统级别。当您导入一个module or a package,Python创建的对应对象总是类型module
。但请注意,当您导入package,仅变量/函数/类__init__.py
那个文件package是直接可见的,not 子包 or modules.
Example
作为一个例子,考虑xml
Python标准库中的包:其xml
目录包含一个__init__.py
文件和四个子目录;子目录etree
包含一个__init__.py
文件,以及除其他外,ElementTree.py
file.
看看当您尝试交互式导入包/模块时会发生什么:
>>> 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
在Python中也有built-in https://docs.python.org/3/tutorial/modules.html#standard-modules模块,例如sys
,是用 C 编写的,但我认为您无意考虑问题中的那些内容。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)