第5章 模块与函数
本章知识点:
1、模块的创建与使用;
2、内置模块;
3、常用模块;
4、函数的创建和使用;
5、lambda 函数;
6、Generator 函数;
7、函数化程序设计;
5.1 Python 程序的结构
5.2 模块
5.2.1 模块的创建
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 ## 自定义模块 2 def func(): 3 print ("MyModule.func()") 4 5 class MyClass: 6 def myFunc(self): 7 print ("MyModule.MyClass.myFunc()")
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 ## 调用自定义模块的类和函数 2 import myModule 3 4 myModule.func() # 输出:MyModule.func() 5 myClass = myModule.MyClass() # 变量 6 myClass.myFunc() # 输出:MyModule.MyClass.myFunc()
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 # 模块 myModule 2 count = 1 3 def func(): 4 global count 5 count = count + 1 6 return count 7 8 9 10 11 print ("count =",myModule.func()) 12 myModule.count = 10 13 print ("count =",myModule.func()) 14 15 import myModule 16 print ("count =",myModule.func()) 17 # 输出:count = 2 18 # count = 11 19 # count = 12
5.2.3 模块的属性
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #myModule.py 2 if __name__ == '__main__': 3 print ('myModule作为主程序运行') 4 else: 5 print ('myModule被另一个模块调用') 6 7 import myModule 8 print (__doc__)
5.2.4 模块的内置函数
1、apply()
2、filter()
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 def func(x): 2 if x > 0: 3 return x 4 print (filter(func, range(-9, 10))) 5 print (list(filter(func, range(-9, 10)))) 6 # 输入:<filter object at 0x000001B9B4D9C080> 7 # [1, 2, 3, 4, 5, 6, 7, 8, 9]
3、reduce()
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 def sum(x,y): 2 return x + y 3 from functools import reduce 4 print (reduce(sum, range(0, 10))) 5 print (reduce(sum, range(0, 10), 10)) 6 print (reduce(sum, range(0, 0), 10)) 7 # 输出:45;55;10
4、map()
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 def power(x): 2 return x ** x 3 print (map(power, range(1, 5))) 4 print (list(map(power, range(1, 5)))) 5 def power1(x, y): 6 return x ** y 7 print (map(power1, range(1, 5), range(5, 1, -1))) 8 print (list(map(power1, range(1, 5), range(5, 1, -1)))) 9 # 输入:<map object at 0x000001BCEAF2A710> 10 # [1, 4, 27, 256] 11 # <map object at 0x000001BCEB0C8DA0> 12 # [1, 16, 27, 16]
5.2.5 自定义包
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 if __name__ == "__main__": 2 print ("作为主程序运行") 3 else: 4 print ("pack初始化") 5 # 输出:作为主程序运行
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 def func(): 2 print ("pack.myModule.func()") 3 4 if __name__ == "__main__": 5 print ("myModule作为主程序运行") 6 else: 7 print ("myModule被另一个程序调用") 8 # 输出:myModule作为主程序运行
5.3 函数
5.3.1 函数的定义
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 ## 函数的定义 2 from __future__ import division 3 def arithmetic(x, y ,operator): 4 result = { 5 "+": x + y, 6 "-": x - y, 7 "*": x * y, 8 "/": x / y 9 } 10 11 ## 函数的调用 12 print (arithmetic(1, 2, "+"))
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 def arithmetic(x=1, y=2, operator="+"): 2 result = { 3 "+": x + y, 4 "-": x - y, 5 "*": x * y, 6 "/": x / y 7 } 8 return result.get(operator) 9 10 ## 函数的调用 11 print (arithmetic(1, 2)) 12 print (arithmetic(1, 2, "-")) 13 print (arithmetic(y=3,operator="-")) 14 print (arithmetic(x=4, operator="-")) 15 print (arithmetic(y=3,x=4, operator="-")) 16 # 输出:3 17 # -1 18 # -2 19 # 2 20 # 1
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 ## 列表作为参数的传递 2 def arithmetic(args=[], operator="+"): 3 x = args[0] 4 y = args[1] 5 result = { 6 "+": x + y, 7 "-": x - y, 8 "*": x * y, 9 "/": x / y 10 } 11 return result.get(operator) 12 print (arithmetic([1, 2])) 13 # 输出:3
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 def append(args=[]): 2 args.append(0) 3 print (args) 4 append() 5 append([1]) 6 append() 7 # 输出:[0] 8 # [1, 0] 9 # [0, 0]
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 def append(args=[]): 2 if len(args) <= 0: 3 args = [] 4 args.append(0) 5 print (args) 6 append() 7 append([1]) 8 append() 9 # 输出:[0] 10 # [1, 0] 11 # [0]
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 ## 传递可变参数 2 def func(*args): 3 print (args) 4 func(1, 2, 3) 5 # 输出:(1, 2, 3)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 def search(*t, **d): 2 keys = d.keys() 3 values = d.values() 4 print (keys) 5 print (values) 6 for arg in t: 7 for key in keys: 8 if arg == key: 9 print ("find:",d[key]) 10 11 search("one", "three", one="1", two="2", three="3") 12 # 输入:dict_keys(['one', 'two', 'three']) 13 # dict_values(['1', '2', '3']) 14 # find: 1 15 # find: 3
5.3.3 函数的返回值
## 没有return语句的返回值 def func(): pass print (func()) # 输出:None
## return返回多个值 def func(x, y, z): l = [x, y, z] l.reverse() numbese = tuple(l) return numbese x, y , z = func(0, 1, 2) print (x, y, z) # 输出:2 1 0
def func(x, y, z): l = [x, y, z] l.reverse() a, b, c = tuple(l) return a, b, c x, y , z = func(0, 1, 2) print (x, y, z) # 输出:2 1 0
def func(x): if x > 0: return "x > 0" elif x == 0: return "x == 0" else: return "x < 0" print (func(-2)) # 输出:x < 0
## 多个return语句的重构 def func(x): if x > 0: result = "x > 0" elif x == 0: result = "x == 0" else: return "x < 0" return result print (func(-2)) # 输出:x < 0
5.3.4 函数的嵌套
## 嵌套函数 def sum(a,b): return a + b def sub(a, b): return a - b def func(): x = 1 y = 2 m = 3 n = 4 return sum(x, y) * sub(m, n) print (func()) # 输出:-3
## 嵌套函数 def func(): x = 1 y = 2 m = 3 n = 4 def sum(a, b): return a + b def sub(a, b): return a - b return sum(x, y) * sub(m, n) print (func()) # 输出:-3
## 嵌套函数,直接使用外层函数的变量 def func(): x = 1 y = 2 m = 3 n = 4 def sum(): return x + y def sub(): return m - n return sum() * sub() print (func()) # 输出:-3
5.3.5 递归函数
## 计算阶乘 def refunc(n): i = 1 if n > 1: i = n n = n * refunc(n-1) print ("%d! =" %i, n) return n refunc(5) # 输出:1! = 1 # 2! = 2 # 3! = 6 # 4! = 24 # 5! = 120
5.3.6 lambda函数
## lambda函数 def func(): x = 1 y = 2 m = 3 n = 4 sum = lambda x, y : x + y print (sum) sub = lambda m, n : m - n print (sub) return sum(x, y) * sub(m, n) print (func()) # 输出:<function func.<locals>.<lambda> at 0x000001652324E158> # <function func.<locals>.<lambda> at 0x0000016523239C80> # -3
# ## lambda函数的用法 print ((lambda x:-x)(-2)) #输出:2
5.3.7 Generator函数
## 定义Generator函数 def func(n): for i in range(n): yield i # 在for循环中输出 for i in func(3): print (i) # 使用next()输出 r = func(3) print (r.next()) print (r.next()) print (r.next())
## yield与return区别 def func(n): for i in range(n): return i def func2(n): for i in range(n): yield i print (func(3)) f = func2(3) print (f) print (f.next()) print (f.next())