Python之路,第十三篇:Python入门与基础13

python3   模块

模块 Module

概念: 模块是一个保护有一系统变量、函数、类等组成的程序组;

            模块是一个文件,模块文件名通常以.py 结尾;

作用:让一些相关的变量,函数, 类等有逻辑的组织在一起,让逻辑结构更清晰;

            模块中的变量,函数和类等可供其他模块或程序使用;

 分类: 1,内置模块(builtins), 在解析器的内部可以直接使用;

            ,2,安装的标准库模块,安装python时已安装都可以使用;

            ,3,第三方模块(通常开源),需要自己安装;

            4,用户自己编写的模块,(可以作为其他人的第三方模块使用)

模块的导入:

          1)  import  语句

                import   模块名1  [ as 模块新名1 ]  [模块名2  [ as 模块新名2 ] ]...

例如:#导入数据模块

            import  math

            #导入系统sys模块和os模块

             import   sys,os

用法:模块名.属性名

            math.factorial(5)    #求5的阶乘

dir(object) 函数,返回模块的所有属性的字符串列表;

help(object) 函数,可以查看模块文档相关的字符串;

 

from   import  语句

语法: from  模块名  import  模块属性名1   [ as 属性别名1  ] ,模块属性名2   [ as 属性别名2 ] ,....

作用: 将某模块内的一个或多个属性导入到当前模块;

示例: from    math  import pi

           from  math  import sin

           from  math  import factorial  as fac

 

from import  * 语句

语法: from   模块名  import   *

作用:将模块内的所有属性名导入到当前模块

示例: from math  import   *

            sin(pi/2)  #1.0

 

dir()  函数

        dir([对象])   #返回一个字符串列表;

作用:  1,如果没有参数调用,则返回当前作用域内所有变量的列表;

              2,如果给定一个对象作为参数,则返回这个对象的所有变量列表;

                         对于模块,返回这个模块的全部变量; 对于类,返回类对象的所有变量;对于其他对象,返回所有变量,类变量,基类变量;

 1 import math
 2 math.factorial(5)
 3 120
 4 dir(math)
 5 ['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'hypot', 'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc']
 6 dir()
 7 ['__builtins__', 'cba', 'math', 'sys']
 8 import math
 9 dir()
10 ['__builtins__', 'cba', 'math', 'sys']
11 dir(math)
12 ['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'hypot', 'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc']
13 dir(pi)
14 Traceback (most recent call last):
15   File "<input>", line 1, in <module>
16 NameError: name 'pi' is not defined
17 from math import pi
18 dir()
19 ['__builtins__', 'cba', 'math', 'pi', 'sys']
20 pi
21 3.141592653589793
22 import os
23 dir()
24 ['__builtins__', 'cba', 'math', 'os', 'pi', 'sys']
25 from os import *
26 dir()
27 ['F_OK', 'O_APPEND', 'O_BINARY', 'O_CREAT', 'O_EXCL', 'O_NOINHERIT', 'O_RANDOM', 'O_RDONLY', 'O_RDWR', 'O_SEQUENTIAL', 'O_SHORT_LIVED', 'O_TEMPORARY', 'O_TEXT', 'O_TRUNC', 'O_WRONLY', 'P_DETACH', 'P_NOWAIT', 'P_NOWAITO', 'P_OVERLAY', 'P_WAIT', 'R_OK', 'SEEK_CUR', 'SEEK_END', 'SEEK_SET', 'TMP_MAX', 'W_OK', 'X_OK', '__builtins__', '_exit', 'abort', 'access', 'altsep', 'cba', 'chdir', 'chmod', 'close', 'closerange', 'cpu_count', 'curdir', 'defpath', 'device_encoding', 'devnull', 'dup', 'dup2', 'environ', 'error', 'execl', 'execle', 'execlp', 'execlpe', 'execv', 'execve', 'execvp', 'execvpe', 'extsep', 'fdopen', 'fsdecode', 'fsencode', 'fstat', 'fsync', 'get_exec_path', 'get_handle_inheritable', 'get_inheritable', 'get_terminal_size', 'getcwd', 'getcwdb', 'getenv', 'getlogin', 'getpid', 'getppid', 'isatty', 'kill', 'linesep', 'link', 'listdir', 'lseek', 'lstat', 'makedirs', 'math', 'mkdir', 'name', 'open', 'os', 'pardir', 'path', 'pathsep', 'pi', 'pipe', 'popen', 'putenv', 'read', 'readlink', 'remove', 'removedirs', 'rename', 'renames', 'replace', 'rmdir', 'sep', 'set_handle_inheritable', 'set_inheritable', 'spawnl', 'spawnle', 'spawnv', 'spawnve', 'startfile', 'stat', 'stat_float_times', 'stat_result', 'statvfs_result', 'strerror', 'supports_bytes_environ', 'symlink', 'sys', 'system', 'terminal_size', 'times', 'times_result', 'umask', 'uname_result', 'unlink', 'urandom', 'utime', 'waitpid', 'walk', 'write']
View Code

 内置模块:builtins   , sys, time,itertools.....math

标准库模块: random, os, datetime   , xml .....

http://docs.python.org

 

时间模块   time

      此模块提供了时间相关的函数,且一直可用;

导入方式: import time  ;   from  time  import *   ; from time  import   xxx

时间简介:

         公元纪年是公元0000年1月1日开始;

         对于uninx、linux 系统,计算机元年是从1970年1月1日0时开始,此时时间为0 ;

         UTC(Coordinated  Universal Time) 是从Greewich 时间开始计算的;UTC时间不会因时区问题而产生错误  ;

         DST阳光节约时间(Daylight Saving Time) 又称夏令时,是经过日照时间修正后的时间;

时间元组:

是一个9个整数组成的,这个9个元素自前至后依次为为:

四位的年(例1999)

月(1-12)

日(1-31)

时(0-23)

分(0-59)

秒(0-59)

星期(0-6,星期一是0)

元旦开始日(1-366)

夏令修正时间(-1,0  或1)

注:如果年份小于100,则自动转换为加上1900后的值;

模块中的变量和函数

变量

time.timezone   本地区时间与UTC时间差(秒为单位)

time.altzone      夏令时时间与UTC时间差(秒为单位)

time.daylight      夏令时校正时间

time.tzname      时区名称的元组

函数

time.time                          返回计算机元年至当前时间的秒数的浮点数(UTC时间为准)

time.sleep(secs)             让程序按给定的秒数睡眠一段时间;

time.gmtime([secs])        将给定的秒数转换为UTC表达的时间元组;

time.mktime(tuple)          将时间元组转换为新纪元秒数时间(UTC为准)

time.asctime( [tuple] )      将时间元组转换为字符串;

time.localtime([secs])     将UTC秒数转换为时间元组(以本地时间为准)

time.clock()                     返回CPU自开始运行到现在的时间秒数的浮点数;

 [ ] 里的内容 代表可以省略

 

数学模块  

模块名  math

注:linux下为内建模块,mac os 为标准库模块

变量:

math.e     自然数e

math.pi     圆周率

函数

math.ceil(x) 对x向上取整, 比如x=1.2 ,返回2
math.floor(x) 对x向下取整, 比如x=1.2 ,返回1
math.sqrt(x) 返回x的平方根
math.factorial(x) 求x的阶乘
math.log(x[, base]) 返回以base为底x的对数,如果不给出base,则以自然对数e为底;
math.log10(x) 求以10为底x的对数
math.pow(x,y) 返回x**y
math.fabs(x) 返回浮点数x的绝对值
#角度和弧度转换
math.degrees(x) 将弧度x转换为角度
math.redians(x) 将角度x转换为弧度
#三角函数
math.sin(x) 返回x的正弦(x为弧度)
math.cos(x) 返回x的余弦
math.tan(x) 返回x的正切

 

math.asin(x) 返回x的反正弦(x为弧度)
math.acos(x) 返回x的反余弦
math.atan(x) 返回x的反正切

 

 系统模块sys

         与系统相关的信息

数据:

sys.path       模块搜索路径 path[0] 是当前脚本程序的路径名,或者是‘ ’ ;

sys.modules    已加载模块的字典;

sys.version      版本信息

sys.version_info   版本信息的命名元组

sys.argv        命令行参数 argv[0]  代表当前脚本程序路径名;

sys.copyright        获取python版本相关信息

sys.builin_module_names     获得python 内建模块名称(字符串元组)

 1 sys.path
 2 sys.path[0]
 3 sys.path[1]
 4 sys.modules
 5 sys.modules[0]
 6 sys.version
 7 sys.version[1]
 8 sys.version_info
 9 sys.version.major
10 sys.argv
11 sys.argv[0]
12 sys.copyright
13 sys.builtin_module_names
14 ('_ast', '_bisect', '_codecs', '_codecs_cn', '_codecs_hk', '_codecs_iso2022', '_codecs_jp', '_codecs_kr', '_codecs_tw', '_collections', '_csv', '_datetime', '_functools', '_heapq', '_imp', '_io', '_json', '_locale', '_lsprof', '_md5', '_multibytecodec', '_opcode', '_operator', '_pickle', '_random', '_sha1', '_sha256', '_sha512', '_sre', '_stat', '_string', '_struct', '_symtable', '_thread', '_tracemalloc', '_warnings', '_weakref', '_winapi', 'array', 'atexit', 'audioop', 'binascii', 'builtins', 'cmath', 'errno', 'faulthandler', 'gc', 'itertools', 'marshal', 'math', 'mmap', 'msvcrt', 'nt', 'parser', 'signal', 'sys', 'time', 'winreg', 'xxsubtype', 'zipimport', 'zlib')
View Code

 

 1 import sys
 2 
 3 #sys.argv 是一个字符串序列
 4 print("参数的个数是:",len(sys.argv))
 5 print(sys.argv)
 6 #python3 sys_argv.py  a  b
 7 # #参数的个数是:3
 8 #['sys_argv.py' , 'a' ,  'b']
 9 #
10 #chomod +x sys.argv.py
11 #./sys_argv.py  '-l'  /home/
12 #
13 for x in sys.argv:
14     print("参数是",x)
15 
16 #
17 import sys
18 if len(sys.argv) < 4:
19     print("用法: ./sys_argv.py  数字  运算符 数字")
20     sys.exit(0) #退出程序
21 
22 if  sys.argv[2] == "":
23     print(float(sys.argv[1]) + float(sys.argv[3]))
24 elif sys.argv[2] == "":
25     print(float(sys.argv[1]) * float(sys.argv[3]))
26 #./sys_argv.py  3  加   5   #8
27 #./sys_argv.py  3  乘  5    #15
View Code

 

函数

sys.exit([code])  退出程序, 正常退出时用sys.exit(0)

sys.getrecursionlimit()  得到递归的层次限制值   

sys.setrecursionlimit(n)   设置递归的最大层次限制值

1 sys.getrecursionlimit()
2 1000
3 sys.setrecursionlimit(2000)
4 sys.getrecursionlimit()
5 2000
6 sys.setrecursionlimit(1000)
7 sys.getrecursionlimit()
8 1000
View Code

 

自定义模块的编写:

 1 #file : mymod.py
 2 def fac(n):
 3     print("正在计算n的阶乘...")
 4 
 5 def sum_fac(n):
 6     print("正在计算n的阶乘的和...")
 7     
 8 #import mymod.py
 9 #dir(mymod)
10 #mymod.fac(100)  
11 #mymod.sum_fac(100)
12 
13 ##################################################
14 #test_mymod.py
15 import mymod
16 mymod.fac(20)
17 mymod.sum_fac(30)
18 #
19 from mymod import fac as f
View Code

 

模块的搜索路径:

import  模块名     #对应   模块名.py   去哪找?

查找的顺序:1, 搜索内置模块 sys.builtins_modules_name

                       2,sys.path 提供路径

                       3,搜索程序运行时路径(绝对路径/当前路径)

PYTHONPATH 环境变量

此环境变量的值会在python3的解析器启动时自动加载到sys.path 中;

#export    PYTHONPATH=$PYTHONPATH:/home/tarena

#printenv

1 sys.builtin_module_names
2 ('_ast', '_bisect', '_codecs', '_codecs_cn', '_codecs_hk', '_codecs_iso2022', '_codecs_jp', '_codecs_kr', '_codecs_tw', '_collections', '_csv', '_datetime', '_functools', '_heapq', '_imp', '_io', '_json', '_locale', '_lsprof', '_md5', '_multibytecodec', '_opcode', '_operator', '_pickle', '_random', '_sha1', '_sha256', '_sha512', '_sre', '_stat', '_string', '_struct', '_symtable', '_thread', '_tracemalloc', '_warnings', '_weakref', '_winapi', 'array', 'atexit', 'audioop', 'binascii', 'builtins', 'cmath', 'errno', 'faulthandler', 'gc', 'itertools', 'marshal', 'math', 'mmap', 'msvcrt', 'nt', 'parser', 'signal', 'sys', 'time', 'winreg', 'xxsubtype', 'zipimport', 'zlib')
3 
4 sys.path
5 #import sys
6 #sys.path.append("/home/test/")
7 #import  mymod
8 #dir()
View Code
1 printenv
2 echo $PATH
3 export PATH=$PATH:/home/test/
4 echo $PATH
5 mymod
View Code

模块加载过程:

1,在模块导入时,模块内的所有语句会执行;

2,如果一个模块已经导入,则再次导入时,不会重新执行所有的语句;

模块化编程的优点:

1,有利于多人开发;

2,使代码更加易于维护;

3,提高代码的复用率;

4,模块化变有助于解决函数名和变量名冲突问题;

模块的属性:

__name__属性:

用来记录自身的名字;

1,对于被导入模块,模块名为去掉路径前缀和“.py” 后缀的文件名;

2,对于被执行的主模块,模块名为'__main__'

 1 #mymod.py
 2 
 3 def f1():
 4     print("f1被调用。。")
 5 
 6 def f2():
 7     print("f2被调用。")
 8 
 9 name = "hello"
10 
11 f1()
12 print("模块被加载完毕")
13 ###########
14 >>> import mymod
15 f1被调用。。
16 模块被加载完毕
17 >>> mymod.__name__
18 'mymod'
19 >>>
20 >>> from mymod import f1
21 >>> from mymod import *
22 >>> dir()
23 ['__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'f1', 'f2', 'mymod', 'name']
24 >>>
25 ###################
26 #mymod1.py
27 def f1():
28     print("f1被调用。。")
29 
30 def f2():
31     print("f2被调用。")
32 
33 print("此模块名为:",__name__)
34 #####
35 此模块名为: __main__
36 #####
37 >>> import mymod1
38 此模块名为: mymod1
39 >>>
View Code

 

作用:1,记录模块名,

            2,用来判断是否为主模块;

 1 #mymod2
 2 def f1():
 3     print("f1被调用。。")
 4 
 5 def f2():
 6     print("f2被调用。")
 7 
 8 def test():
 9     print("模块测试正在进行中...")
10     f1()
11     f2()
12 
13 print("此模块名为:", __name__)
14 print("#" * 50)
15 if __name__ == '__main__':
16     test()
17 #此模块名为: __main__
18 ###################################################
19 #模块测试正在进行中...
20 #f1被调用。。
21 #f2被调用。
View Code

 __doc__属性

用来绑定模块的文档字符串;

模块的文档字符串是模块中第一行出现的没给赋值给变量的字符串;

 1 #mymod3.py
 2 '''
 3 此模块有两个函数.
 4 此模块用来演示文档字符串.
 5 此处省略2000字.
 6 '''
 7 
 8 
 9 def f1():
10     print("f1被调用。。")
11 
12 def f2():
13     print("f2被调用。")
14 
15 #>>> import mymod3
16 #>>> dir()
17 #['__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'mymod1', 'mymod3']
18 #>>> mymod3.__doc__
19 #'\n此模块有两个函数.\n此模块用来演示文档字符串.\n此处省略2000字.\n'
20 #>>>
21 #>>> help(mymod3)
22 #Help on module mymod3:
23 #
24 #NAME
25 #    mymod3
26 #
27 #DESCRIPTION
28 #    此模块有两个函数.
29 #    此模块用来演示文档字符串.
30 #    此处省略2000字.
31 #
32 #FUNCTIONS
33 #    f1()
34 #
35 #    f2()
36 #
37 #FILE
View Code
 1 #mymod3.py
 2 '''
 3 此模块有两个函数.
 4 此模块用来演示文档字符串.
 5 此处省略2000字.
 6 '''
 7 
 8 
 9 def f1():
10     '''
11     此为函数的文档字符串
12     此处省略200字
13     '''
14     print("f1被调用。。")
15 
16 
17 def f2():
18     print("f2被调用。")
19 
20 
21 #>>>
22 #
23 ## >>> import mymod3
24 #>>> mymod3.__doc__
25 #'\n此模块有两个函数.\n此模块用来演示文档字符串.\n此处省略2000字.\n'
26 #>>> mymod3.f1.__doc__
27 #'\n    此为函数的文档字符串\n    此处省略200字\n    '
28 #>>> help(mymod3)
29 #Help on module mymod3:
30 #
31 #NAME
32 #    mymod3
33 #
34 #DESCRIPTION
35 #    此模块有两个函数.
36 #    此模块用来演示文档字符串.
37 #    此处省略2000字.
38 #
39 #FUNCTIONS
40 #    f1()
41 #        此为函数的文档字符串
42 #        此处省略200字
43 #
44 #    f2()
45 #
View Code

 

__all__属性

作用:

 当用from   import  * 语句导入模块时,只导入__all__列表内的变量(属性)

__all__属性是用来存放可导出属性的列表;

 

 1 #mymod4.py
 2 __all__ = [ 'hello1', 'hello2', 'hello3','name1' ]
 3 def  hello1():pass
 4 
 5 def  hello2():pass
 6 
 7 def  hello3():pass
 8 
 9 def  hello4():pass
10 
11 def  hello5():pass
12 
13 name1 = 'aaa'
14 name2 = 'bbb'
15 
16 #>>> from mymod4 import *
17 #>>> dir()
18 #['__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'hello1', 'hello2', 'hello3', 'hello4
19 #', 'hello5', 'mymod3', 'mymod4', 'name1', 'name2']
20 #>>>
21 #加'__all__'
22 #>>> from mymod4 import *
23 #>>> dir()
24 #['__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'hello1', 'hello2', 'hello3', 'name1'
25 #]
26 #>>>
View Code

 

 __file__ 属性

 __file__ 用来记录模块对应的文件路径名;

模块的隐藏属性

      模块中以‘_’ 或‘__’ 开头,不以‘__’结尾的属性,在用from xxx import *  语句导入时,将不被导入到其他模块;

 1 #mymod5.py
 2 def _abc():
 3     pass
 4 
 5 def __abc():
 6     pass
 7 
 8 def abc():
 9     pass
10 
11 name = "hello"
12 _name = "hello2"
13 __world = "world..."
14 
15 #>>> from mymod5 import *
16 #>>> dir()
17 #['__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'abc', 'name']
18 #>>> abc
19 #<function abc at 0x00000000026DAE18>
20 #>>> _abc
21 #Traceback (most recent call last):
22 #  File "<stdin>", line 1, in <module>
23 #NameError: name '_abc' is not defined
24 #>>> name
25 #'hello'
26 #>>> _name
27 #Traceback (most recent call last):
28 #  File "<stdin>", line 1, in <module>
29 #NameError: name '_name' is not defined
30 #>>>
31 #
View Code

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

           

           

 

posted on 2018-05-13 12:45  微子天明  阅读(267)  评论(0编辑  收藏  举报

导航