Python基础-week04
Python基础-week04
本节内容摘要:#Author:http://www.cnblogs.com/Jame-mei
-
装饰器
-
迭代器&生成器
-
Json & pickle 数据序列化
-
软件目录结构规范
-
作业:ATM项目开发
一.装饰器
1.定义:本质是函数,装饰其他函数就是为其他函数添加附加功能。
2.原则:a.不能修改被装饰的函数的源代码 b.不能修改被装饰的函数的调用方式。
实例1:装饰器的使用
1 #Author:http://www.cnblogs.com/Jame-mei 2 #装饰器的使用 3 import time 4 5 6 def timmer(func): 7 def warpper(*args,**kwargs): 8 start_time=time.time() 9 func() 10 stop_time=time.time() 11 print ("The func run time is %s" %(stop_time-start_time)) 12 return warpper 13 14 15 16 17 18 @timmer #等于 time1=timmer(time1),最后再time1() 19 def time1(): 20 time.sleep(2) 21 print ("in the test1...............") 22 23 24 time1()
实例1:装饰器的使用
实例2:一个函数调用另一个函数,匿名函数的使用
1 #Author:http://www.cnblogs.com/Jame-mei 2 3 def foo(): 4 print ("in the foo") 5 bar() 6 7 8 9 #foo() 调用bar报错,因为要将foo()放到函数的后面,因为Python是解释型语言,需要逐行翻译! 10 11 def bar(): #bar()可以放在调用函数的foo的后面 12 print ("in the bar") 13 14 15 calc=lambda x:x*3 #匿名函数的使用 16 17 foo() 18 19 print (calc(10))
实例2:调用其他函数和匿名函数的使用
3.实现装饰器的知识储备:
1).函数即”变量”,见下图:
其中变量名x,y和函数名test ,本质他们都是内存中的一个地址,所以函数和变量一样,只不过函数通过()来调用。
2).高阶函数
a.把一个函数名当作实参传给另外一个函数(在不修改被装饰函数的源代码的情况下,为其添加附加功能)
b.返回值中包含函数名(不修改函数的调用方式)
实例3:高阶函数的2个功能
1 #Author:http://www.cnblogs.com/Jame-mei 2 #高阶函数的2个功能 3 4 import time 5 6 7 8 #1.把一个函数当作实参传给另外一个函数 9 def bar(): 10 time.sleep(2.5) 11 print ('in the bar') 12 13 def foo(func): 14 start_time=time.time() 15 func() #bar 的运行时间 16 stop_time=time.time() 17 print ("the func run time is %s" %(stop_time-start_time)) 18 19 20 #foo() 原来的调用方式 21 foo(bar) 22 ------------------------------------output--------------------------------------------------- 23 24 in the bar 25 the func run time is 2.500143051147461 26 27 Process finished with exit code 0
把一个函数名当作另一个函数的实参
1 #Author:http://www.cnblogs.com/Jame-mei 2 #高阶函数的2个功能 3 #2.返回值中包含函数 4 5 def bar(): 6 time.sleep(2.5) 7 print ('in the bar') 8 9 def test2(func): 10 print (func) #打印的是内存地址 11 return func #返回之中包含函数!! 12 13 14 15 16 bar=test2(bar) 17 bar() #代表bar(),打印print
返回值中包含函数名
3).嵌套函数和作用域
高阶函数+嵌套函数=装饰器
1 #1.函数的嵌套 2 def foo(): 3 print ('in the foo()') 4 def bar(): #在函数内定义另一个函数def ,相当于foo()函数的局部变量。 5 print ('in the bar()') 6 7 bar() #局部变量只能在内部调用!! 8 9 10 11 foo()
a.函数的嵌套
1 #Author:http://www.cnblogs.com/Jame-mei 2 #嵌套函数的全局作用域和局部作用域 3 x=0 4 def grandpa(): 5 x=1 6 def dad(): 7 x=2 8 def son(): 9 x=3 10 print (x) 11 son() 12 dad() 13 14 grandpa() 15 print (x)
b.函数的作用域
1 #3.函数的调用 2 def bar2(): 3 print ('in the bar2') 4 5 def foo2(): 6 print ('in the foo2') 7 bar2() #这叫函数的调用,这里要区别与函数的嵌套!
c.函数的嵌套和调用的区别