
4.5 模块
模块(Module)能够有逻辑地组织Python代码段。把相关的代码分配到一个模块中能让代码更好用,更易懂。简单地说,模块就是一个保存了Python代码的文件。模块中能定义函数、类和变量。
导入Python中的模块和C语言中的头文件同引用Java中的包类似,例如,在Python中要调用sqrt()函数,必须用import关键字导入math这个模块。下面就学习Python中的模块。
4.5.1 import导入模块

模块
1.导入模块的方式
在Python中用关键字import来导入某个模块。方式如下:

例如,要引用模块math,可以在文件最开始的地方用import math来导入。
调用模块中函数的方法如下:

例如:

为什么必须加上模块名进行调用呢?因为可能存在这样一种情况:在多个模块中含有相同名称的函数,此时如果只是通过函数名来调用,解释器无法知道到底要调用哪个函数。所以,如果像上述这样导入模块的时候,调用函数必须加上模块名。
若只需要用到模块中的某个函数,只需要导入该函数即可,导入语句如下:

通过这种方式导入,调用函数时只能给出函数名,不能给出模块名,但是当两个模块中含有相同名称函数时,后面一次导入会覆盖前一次导入。
也就是说,假如模块A中有函数fun(),在模块B中也有函数fun(),如果导入A中的fun()在先、B中的fun()在后,那么当调用fun()函数时,会执行模块B中的fun()函数。
如果想一次性导入math中所有的项目,可以通过:

这是一种简单的导入模块中所有项目的方法,然而不建议过多地使用这种方式。
2.模块位置的搜索顺序
当导入一个模块时,Python解析器对模块位置的搜索顺序如下:
(1)当前目录。
(2)如果不在当前目录,Python则搜索在Python PATH环境变量下的每个目录。
(3)如果都找不到,Python会查看由安装过程决定的默认目录。
模块搜索路径存储在system模块的sys.path变量中。变量中包含当前目录、Python PATH和由安装过程决定的默认目录。例如:

输出结果:

3.列举模块内容
dir(模块名)函数返回一个排好序的字符串列表,内容是模块中定义的变量和函数。例如:

输出结果:

在此,特殊字符串变量_ _name_ _指模块的名字,_ _file_ _指该模块所在文件名,_ _doc_ _指该模块的文档字符串。
4.5.2 定义自己的模块
在Python中,每个Python文件都可以作为一个模块,模块的名字就是文件的名字。
例如,有这样一个文件fibo.py,在fibo.py中定义了3个函数add()、fib()、fib2():

那么在其他文件(如test.py)中就可以按如下方式使用:

加上模块名称来调用函数:

当然,也可以通过from fibo import add,fib,fib2来导入。
用直接函数名调用函数:

如果想列举fibo模块中定义的属性列表,可输入如下语句:

输出结果:

下面学习一些常用标准模块。
4.5.3 time模块
在Python中,通常有2种方式来表示时间:
(1)时间戳,是从1970年1月1日00:00:00开始到现在的秒数。
(2)时间元组struct_time,其中共有9个元素。具体如下:
tm_year(年比如2011)、tm_mon(月)、tm_mday(日)、tm_hour(小时,0-23)、tm_min(分,0-59)、tm_sec(秒,0-59)、tm_wday(星期,0–6,0表示周日)、tm_yday(一年中的第几天,1-366)、tm_isdst(是否是夏令时,默认为1夏令时)。
time模块包含既有时间处理的、也有转换时间格式的函数,如表4-5所示。
表4-5 time模块中的函数

例如:

4.5.4 calendar模块
此模块的函数都是与日历相关的,例如打印某月的字符月历。星期一是默认的每周第一天,星期天是默认的最后一天。更改设置需调用calendar.setfirstweekday()函数。calendar模块中包含的函数如表4-6所示。
表4-6 calendar模块中的函数

另外,Python在提供datetime模块支持日期和时间运算的同时,还能更有效地处理和格式化输出。同时该模块还支持时区处理。例如:


4.5.5 random模块
随机数可以用于数学、游戏等领域,还经常被嵌入到算法中,用以提高算法效率,并提高程序的安全性。随机数函数在random模块中,常用的随机数函数如表4-7所示。
表4-7 常用的随机数函数

4.5.6 math模块和cmath模块
math模块实现了许多对浮点数的数学运算函数,这些函数一般是对C语言库中同名函数的简单封装。math模块的数学运算函数如表4-8所示。
表4-8 math模块的数学运算函数

续表

例如:

另外,在Python中cmath模块包含了一些用于复数运算的函数。cmath模块的函数跟math模块函数基本一致,区别是cmath模块运算的是复数,math模块运算的是数学运算。
