先给大家解释一下模块、包、库之间的概念:
模块由上面的内容我们得知模块就是一个 py 文件,这个文本文件中存储着一组功能,方面我们再次使用的时候,提高代码的复用率。我们成这一个的一个 py 文件为 Python 模块(Module)。其他 Python 脚本中,通过 import 载入定义好的 Python 模块。 定义和调用 Python 模块我们先来看如何定义一个 Python 模块。 定义一个 hello.py 模块,内容如下: print("Hello World!") 模块名.函数名 来进行调用import hello # 现在可以调用模块里包含的函数了 hello.sayhello()
from ... import ...模块提供了类似名字空间的限制,允许 Python 从模块中导入指定的符号(变量、函数、类等)到当前模块。导入后,这些符号就可以直接使用,而不需要前缀模块名。 语法如下: from hello import sayhello sayhello() def world(): from hello import * sayhello() world() Python World! 包包(package)是 Python 中对模块的更高一级的抽象。简单来说,Python 允许用户把目录当成模块看待。这样一来,目录中的不同模块文件,就变成了「包」里面的子模块。此外,包目录下还可以有子目录,这些子目录也可以是 Python 包。这种分层,对模块识别、管理,都是非常有好处的。 特别地,对于一些大型 Python 工具包,内里可能有成百上千个不同功能的模块。科学计算领域,SciPy, NumPy, Matplotlib 等第三方工具,都是用包的形式发布的。 包定义常见的包结构如下: -------__init__.py -------moduleName1.py -------moduleName2.py ------- ... __init__.py 文件。-------__init__.py -------calculator.py return a+b def reduce(a,b) : return a-b def multiply(a,b) : return a*b def divide(a,b) : return a/b 使用 Python 包calculator.py import cal.calculator # 使用包的模块的方法 print(cal.calculator.add(1,2)) from ... import ... 语句来简化一下。from cal import calculator # 使用包的模块的方法 print(calculator.multiply(3,6)) 总结本节给大家介绍了 Python 模块和包的使用,对 Python 工程师使用提供了支撑,模块和包的合理使用不断可以提高代码的使用效率,也可以更规范的整个工程项目的调用。 参考: https://ge/2017/07/23/modules-and-packages-of-python/ 系列文章 |
|