1、迭代器特点:
•访问者不需要关心迭代器内部的结构,仅需通过next()方法不断去取下一个内容
•不能随机访问集合中的某个值 ,只能从头到尾依次访问
•访问到一半时不能往回退
•便于循环比较大的数据集合,节省内存
1 a = iter([1,2,3]) 2 a 3 <list_iterator object at 0x101402630> 4 a.__next__() 5 1 6 a.__next__() 7 2 8 a.__next__() 9 3
2、生成器generator:
•一个函数调用时返回一个迭代器,那这个函数就叫做生成器(generator),如果函数中包含yield语法,那这个函数就会变成生成器;
1 def cash_money(amount): 2 while amount >0: 3 amount -= 100 4 yield 100 5 print('又来取钱了') 6 atm = cash_money(500) 7 print(type(atm)) 8 print(atm.__next__()) 9 print(atm.__next__()) 10 print('叫个大保健') 11 print(atm.__next__())
•实现并发运算:
1 import time 2 def consume(name): 3 print('%s 准备吃包子!' %name) 4 while True : 5 baozi = yield 6 print('包子[%S],被[%s]吃了!' %(baozi,name)) 7 def produce(name): 8 c = consume('A') 9 c2 = consume('B') 10 c.__next__() 11 c2.__next__() 12 print('老子开始做包子了!') 13 for i in range(10): 14 time.sleep(1) 15 print('做了2个包子!') 16 c.send(i) 17 c2.send(i)
3、装饰器:
•装饰器1
1 def loginin(fun): 2 print('passed user verification...') 3 return fun #返回tv的函数地址 4 def tv(): 5 print('Welcome %s to home page' ) 6 tv = loginin(tv) #将tv的函数地址传给fun 7 tv() #验证结束后,加上括号执行tv函数
•装饰器2
1 def login(func): 2 def inner(arg): 3 print('passed user verification...') 4 func(arg) 5 return(inner) 6 @login 7 def tv(name): 8 print('Welcome %s to home page' %name) 9 tv('alex')
•多层装饰器
1 def Before(request,kargs): 2 print ('before') 3 def After(request,kargs): 4 print ('after') 5 def Filter(before_func,after_func): 6 def outer(main_func): 7 def wrapper(request,kargs): 8 before_result = before_func(request,kargs) 9 main_result = main_func(request,kargs) 10 after_result = after_func(request,kargs) 11 return wrapper 12 return outer 13 @Filter(Before, After) 14 def Index(request,kargs): 15 print ('index') 16 Index('alex','ddd')
4、递归实验:
1 def calc(n): 2 print(n) 3 if n/2 >1: 4 res = calc(n/2) 5 print('res:',res) 6 print('N:',n) 7 return n 8 calc(10)