1、 列表生成器:代码例子
1 a=[i*2 for i in range(10)] 2 print(a) 3 4 运行效果如下: 5 D:python35python.exe D:/python培训/s14/day4/列表生成式.py 6 [0, 2, 4, 6, 8, 10, 12, 14, 16, 18] 7 8 Process finished with exit code 0
2、高阶函数
变量可以指向函数,函数的参数能接受变量,即把一个函数名当做实参传给另外一个函数
返回值中包涵函数名
代码例子:
1 def test(): 2 print("int the test") 3 4 def test2(func): 5 print("in the test2") 6 print(func) 7 func() 8 9 test2(test) 10 运行效果如下: 11 D:python35python.exe D:/python培训/s14/day4/高阶函数.py 12 in the test2 13 <function test at 0x000000000110E268> #这里是test的内存地址 14 int the test 15 16 Process finished with exit code 0
3、装饰器
装饰器:本质是函数,(装饰其他函数)就是为其他函数添加附加功能
装饰器原则:
a.不能修改被装饰的函数的源代码
b.不能修改被装饰的函数的调用方式
实现装饰器的知识储备:
a、函数即“变量”
b、高阶函数
c、嵌套函数
高阶函数+嵌套函数=====装饰器
高阶函数:
a.把一个函数名当做实参传给另外一个函数
b.返回值中包含函数名
代码例子
1 import time 2 def timeer(func): 3 def warpper(): 4 start_time=time.time() 5 func() 6 stop_time=time.time() 7 print("the fun runn time is %s" %(stop_time-start_time)) 8 return warpper 9 @timeer 10 def test1(): 11 time.sleep(3) 12 print("in the test1") 13 14 test1() 15 运行结果如下: 16 D:python35python.exe D:/python培训/s14/day4/装饰器.py 17 in the test1 18 the fun runn time is 3.000171661376953 19 20 Process finished with exit code 0
带参数的装饰器
1 import time 2 3 def timer(func): 4 def deco(*args,**kwargs): 5 start_time=time.time() 6 func(*args,**kwargs) 7 stop_time=time.time() 8 print("the func runn time is %s" %(stop_time-start_time)) 9 return deco 10 11 @timer #test1 = timer(test1) 12 def test1(): 13 time.sleep(3) 14 print("in the test1") 15 16 @timer 17 18 def test2(name,age): 19 print("name:%s,age:%s" %(name,age)) 20 21 test1() 22 test2("zhaofan",23) 23 运行结果如下: 24 25 D:python35python.exe D:/python培训/s14/day4/装饰器3.py 26 in the test1 27 the func runn time is 3.000171661376953 28 name:zhaofan,age:23 29 the func runn time is 0.0 30 31 Process finished with exit code 0
终极版的装饰器
1 import time 2 user,passwd = "zhaofan","123" 3 def auth(auth_type): 4 print("auth func:",auth_type) 5 def outer_wrapper(func): 6 def wrapper(*args,**kwargs): 7 if auth_type=="local": 8 username = input("Username:").strip() 9 password = input("Password:").strip() 10 if user == username and passwd== password: 11 print("