Python教程-Python模块

在本教程中,我们将解释如何构建和导入自定义Python模块。此外,我们还可以通过各种方法导入或集成Python的内置模块。
什么是模块化编程?
模块化编程是将单个复杂的编程任务分割为多个更简单、易于管理的子任务的实践。我们称这些子任务为模块。因此,我们可以通过组装不同的模块来构建更大的程序,这些模块就像构建块一样发挥作用。
在大型应用程序中将代码模块化具有许多好处。
简化: 模块通常集中在整体问题的相对小的领域,而不是整个任务。如果我们只专注于一个模块,那么我们将有一个更易于管理的设计问题。程序开发现在更简单,错误也更少。
灵活性: 模块经常用于在不同的问题领域之间建立概念上的分离。如果模块的构建方式减少了相互关联,那么更改一个模块不太可能影响程序的其他部分。它增加了许多开发人员能够在一个大型项目上进行合作的可能性。
可重用性: 在特定模块中创建的函数可以轻松地被分配到任务的不同部分(通过适当建立的 API)。因此,不再需要重复的代码。
作用域: 模块通常声明了一个独立的命名空间,以防止在程序的不同部分中发生标识符冲突。
在Python中,通过使用函数、模块和包来鼓励对代码进行模块化。
Python中的模块是什么?
用Python编写的带有函数定义和各种语句的文档称为Python模块。
在Python中,我们可以通过以下3种方式之一来定义一个模块:
- Python本身允许创建模块。
- 类似于re(正则表达式)模块,一个模块可以主要用C编程语言编写,然后在运行时动态插入。
- 内置模块,如itertools模块,已经内置在解释器中。
模块是包含Python代码、函数定义、语句或类的文件。一个名为example_module.py的文件是一个我们将创建的模块,其名称为example_module。
我们使用模块将复杂的程序分解为更小、更易于理解的部分。模块还允许代码的重复使用。
与将其定义复制到多个应用程序中不同,我们可以将最常用的函数定义在一个单独的模块中,然后导入整个模块。
让我们来构建一个模块。在输入以下内容后,将文件保存为example_module.py。
示例:
# Here, we are creating a simple Python program to show how to create a module.
# defining a function in the module to reuse it
def square( number ):
# here, the above function will square the number passed as the input
result = number ** 2
return result # here, we are returning the result of the function
在这里,一个名为example_module的模块包含函数square()的定义。该函数返回给定数字的平方。
如何在Python中导入模块?
在Python中,我们可以从一个模块导入函数,或者如我们所说的,从另一个模块导入函数。
为此,我们使用import关键字。在Python窗口中,我们将在import关键字后添加要导入的模块的名称。我们将导入之前定义的example_module模块。
语法:
import example_module
在这个示例_module中定义的函数不会立即导入到当前程序中。这里只是导入了模块的名称,即example_module。
我们可以使用点运算符通过模块名来使用这些函数。例如:
示例:
# here, we are calling the module square method and passing the value 4
result = example_module.square( 4 )
print("By using the module square of number is: ", result )
输出:
By using the module square of number is: 16
Python有许多标准模块。Python标准模块的完整列表是可用的。可以使用help命令查看列表。
与导入我们的模块一样,用户定义的模块,我们可以使用import语句来导入其他标准模块。
可以通过多种方式来导入模块。以下是其中的一些方法。
Python的import语句
使用import关键字和点运算符,我们可以导入一个标准模块并访问其中定义的函数。以下是一个示例。
代码:
# Here, we are creating a simple Python program to show how to import a standard module
# Here, we are import the math module which is a standard module
import math
print( "The value of euler's number is", math.e )
# here, we are printing the euler's number from the math module
输出:
The value of euler's number is 2.718281828459045
导入并重命名
在导入模块时,我们也可以更改其名称。以下是一个示例。
代码:
# Here, we are creating a simple Python program to show how to import a module and rename it
# Here, we are import the math module and give a different name to it
import math as mt # here, we are importing the math module as mt
print( "The value of euler's number is", mt.e )
# here, we are printing the euler's number from the math module
输出:
The value of euler's number is 2.718281828459045
在这个程序中,math模块现在被命名为mt。在某些情况下,如果模块名称很长,这可以帮助我们更快地键入。
请注意,现在我们的程序范围不再包括术语math。因此,在这种情况下,mt.pi才是模块的正确实现,而math.pi是无效的。
Python的from...import语句
我们可以从模块中导入特定名称,而不是整个模块。以下是一个示例。
代码:
# Here, we are creating a simple Python program to show how to import specific
# objects from a module
# Here, we are import euler's number from the math module using the from keyword
from math import e
# here, the e value represents the euler's number
print( "The value of euler's number is", e )
输出:
The value of euler's number is 2.718281828459045
在这种情况下,只导入了math模块中的e常数。
在这些情况下,我们避免使用点(.)运算符。如下,我们可以同时导入多个属性:
代码:
# Here, we are creating a simple Python program to show how to import multiple
# objects from a module
from math import e, tau
print( "The value of tau constant is: ", tau )
print( "The value of the euler's number is: ", e )
输出:
The value of tau constant is: 6.283185307179586
The value of the euler's number is: 2.718281828459045
导入所有名称 - 使用from...import * 语句
为了在当前命名空间内导入模块中的所有对象,可以使用 * 符号以及from和import关键字。
语法:
from name_of_module import *
使用符号 有利有弊。除非我们确定模块的特定需求,否则不建议使用 。
以下是一个相同的示例。
代码:
# Here, we are importing the complete math module using *
from math import *
# Here, we are accessing functions of math module without using the dot operator
print( "Calculating square root: ", sqrt(25) )
# here, we are getting the sqrt method and finding the square root of 25
print( "Calculating tangent of an angle: ", tan(pi/6) )
# here pi is also imported from the math module
输出:
Calculating square root: 5.0
Calculating tangent of an angle: 0.5773502691896257
模块的路径定位
在Python程序中导入模块时,解释器会搜索多个位置。如果没有找到内置模块,则会搜索多个目录。可以使用sys.path来访问目录列表。Python解释器在下面描述的方式中查找模块:
首先,在当前工作目录中查找模块。然后,如果模块在当前目录中找不到,Python将在shell参数PYTHONPATH中的每个目录中查找。一组文件夹组成了名为PYTHONPATH的环境变量。如果仍然找不到,Python将在下载Python时设置的依赖于安装的文件夹中查找。
以下是一个打印路径的示例。
代码:
# Here, we are importing the sys module
import sys
# Here, we are printing the path using sys.path
print("Path of the sys module in the system is:", sys.path)
输出:
Path of the sys module in the system is:
['/home/pyodide', '/home/pyodide/lib/Python310.zip', '/lib/Python3.10', '/lib/Python3.10/lib-dynload', '', '/lib/Python3.10/site-packages']
内置函数dir()
我们可以使用dir()方法来识别模块内声明的名称。
例如,标准模块str中有以下名称。为了打印这些名称,我们将使用dir()方法,如下所示:
代码:
# Here, we are creating a simple Python program to print the directory of a module
print( "List of functions:\n ", dir( str ), end=", " )
输出:
(输出内容因长度限制而省略)
List of functions:
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'removeprefix', 'removesuffix', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
命名空间和作用域
变量由名字或标识符表示,称为变量。命名空间是一个包含变量名(键)和与其关联的对象(值)的字典。
Python语句可以访问本地和全局命名空间变量。当局部和全局都存在相同名称的两个变量时,局部变量将起到全局变量的作用。每个函数都有一个单独的局部命名空间。类方法的作用域规则与常规函数相同。Python根据合理的预测来确定参数是局部还是全局的。在方法中分配值的任何变量都被视为局部变量。
因此,在函数内部给全局变量赋值之前,我们必须使用global语句。通过global Var_Name语句,Python被告知Var_Name是一个全局变量。Python停止在局部命名空间中查找变量。
例如,我们在全局命名空间中声明了变量Number。由于我们在函数内部为Number提供了一个值,Python将Number视为局部变量。如果我们在声明全局变量之前或之后尝试访问局部变量的值,将会出现UnboundLocalError错误。
代码:
Number = 204
def AddNumber(): # here, we are defining a function with the name Add Number
# Here, we are accessing the global namespace
global Number
Number = Number + 200
print("The number is:", Number)
# here, we are printing the number after performing the addition
AddNumber() # here, we are calling the function
print("The number is:", Number)
输出:
The number is: 204
The number is: 404