一,模块的基本介绍
1,import引入其他标准模块
标准库:Python标准安装包里的模块。
引入模块的几种方式:
i)引入模块:import moduleName
ii)引入模块下的函数:from moduleName import function1,function2,……
iii)引入模块下的所有函数:from moduleName import *
使用模块里的函数的方法:
moduleName.function(agrs)
示例:
1 >>> import math
2 >>> r=math.sqrt(16)
3 >>> print r
4 4.0
如果模块或者函数名字过长可以在import后使用as给该模块取别名,之后可以通过“别名.函数”使用模块里的函数。
示例:
1 >>> import webbrowser as web
2 >>> web.open_new_tab('http://www.cnblogs.com')
3 True
2,使用自定义模块
testfile.py下:
1 def readfile():
2 fr=open('wformat.txt','r')
3 while (1==1):
4 line=fr.readline()
5 if(line==''):
6 break
7 else:
8 print line
9 fr.close()
test.py下:(与testfile.py同在一个目录文件里面)
1 import testfile
2 testfile.readfile()
结果如图:
1 >>> ===================== RESTART ==============================
2 >>>
3 name age sex
4 张三 78 male
5 李四 50 male
6 王五 80 male
7 张强 90 female
调用层次结构:
|
~/|
|
|
|
|tes1.py
|
#调用“testfile模块的程序文件”tes1.py
|
|
|_test
|
#目录test
|
|
|_ _testfile.py
|
#模块文件testfile.py
|
|
|_ _testfile.pyc
|
#模块字节码文件testfile.pyc
|
注意:.pyc是模块字节码文件,在使用模块是Python解释器需要把模块加载到系统里,若发现.py比.pyc新,则需要重新编译生成.pyc,否则不需要。文件.pyc是在第一次加载模块文件时完成的。
如果被调用模块程序与模块程序不在同一个目录文件下,则需要调用os.path.append(模块文件所在的目录)
3,使用模块示例Json模块
1)Python下使用dumps函数可以将Python数据字典转换成Json数据结构。
|
Python |
Json |
|
dict |
object |
|
list,tuple |
array |
|
unicode str |
str |
|
int,long |
number(int) |
|
float |
number(real) |
|
True |
true |
|
False |
false |
示例:
1 import json 2 s=[{'f':(1,3,5,'a'),'x':None}] 3 d=json.dumps(s) 4 print d