版权声明:欢迎转载 https://blog.csdn.net/antony1776/article/details/84144404
1 Python 中的包与模块
python 通过包和模块来管理(变量、函数、类)的命名空间,避免名称冲突,提高代码的可维护性。
模块(Module):就是一个 .py 文件
包(Package): 就是一个包含 __init__.py
文件的目录,__init__.py
可以为空,也可以有 Python 代码,在包导入时被执行。
文章中所用到文件的目录形式:
包: demo, demo.pack
模块: demo.core, demo.test, demo.pack.mod
import demo
import demo.core as c
demo.__name__ == "demo" # True
demo.__file__ # .../demo/__init__.py
c.__name__ == "demo.core" # True
__init__.py
可看做模块名为包名的特殊模块。
2 模块路径
默认情况下,Python 解释器会搜索当前目录、所有已安装的内置模块和第三方模块,搜索路径存放在 sys 模块的 path 变量中。
import sys
sys.path # 模块路径
模块中导入当前包中的其他模块:
# 在 core 模块中导入 test 模块中的方法
from .test import hi as th
# 使用全路径
from demo.test import hi as th
# 以下方式,会导入 sys.path 中的 test 模块或包
import test
注意:
- sys.path 中的当前目录是指 python 解释器执行时的当前目录,在模块定义时,是不可知的。
- 当直接 import test 时,python 会从 sys.path 中搜索,是找不到 demo 包中的 test 的。
- 可以使用
from .modulename import xx
的方式导入当前目录中的其他模块,不能使用import .modulename
- 可以使用全路径访问其他模块
3 导入
import demo # 方法 1
import demo.core as c # 方法 2
from demo.core import * # 方法 3
from demo.core import hello as h # 方法 4
- 包是特殊的模块,对应的模块文件是
__init__.py
- import 用来导入模块,不能直接导入模块中的函数
- from 可用来导入模块或者模块中的特定(变量,函数,类)
4 __all__
demo.__init__.py
from .core import *
print("import demo")
demo.core.py
# import .test as test
from .test import hi as thi
# from test import *
def hi():
print("core.hi")
def hello():
print("core.hello")
def test():
thi()
__all__ = ['hello']
demo.test.py
def hi():
print("test.hi")
from demo import * 会导入 demo 中的所有模块
from demo.core import * 只导入 core 模块中 __all__
定义的(变量,函数,类)
在项目开发中,想要将子模块中的重要(变量,函数,类)放到包的命名空间下,就要通过 __all__
来实现!
例如 NumPy 包的 __init__.py
部分代码
在使用 NumPy 包时,只需要 import numpy as np 就可以方便的使用各种函数。