【Python 3.6.1】模块
我们知道一段代码,越长越不好维护,为了便于维护,可以把很多函数或变量分组、分类放到不同的以.py为后缀的文件中,那么这个文件就称之为一个模块(Module)。
可以把模块想象成导入到python以增强其功能的扩展。需要使用特殊人命令import来导入模块。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
[root@dt ~]# python3 Python 3.6.1 (default, Jul 2 2017, 16:09:42) [GCC 4.4.7 20120313 (Red Hat 4.4.7-18)] on linux Type "help", "copyright", "credits" or "license" for more information. >>> >>> import math >>> math.trunc(15.98) 15 >>> >>> math.floor(15.98) 15 >>> exit() [root@dt ~]# ## 我们看math.floor,在python2和python3是有点儿区别的,python2如下 [root@dt ~]# python Python 2.6.6 (r266:84292, Nov 22 2013, 12:16:22) [GCC 4.4.7 20120313 (Red Hat 4.4.7-4)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import math >>> math.floor(15.98) 15.0 >>> |
调用函数的时候每次都要写模块的名字,比较麻烦,在确定函数名不冲突的情况下,可以用下面的命令
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
[root@dt ~]# python3 Python 3.6.1 (default, Jul 2 2017, 16:09:42) [GCC 4.4.7 20120313 (Red Hat 4.4.7-18)] on linux Type "help", "copyright", "credits" or "license" for more information. >>> ## 首先确定trunc函数并不存在 >>> trunc(12.9) Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'trunc' is not defined >>> ## 通过如下方式导入math模块中的trunc函数,导入后,就可以直接使用trunc函数了 >>> from math import trunc >>> trunc(12.9) 12 >>> |