装饰器:
定义:本质是函数,功能是装饰其他函数,就是为其他函数添加附加功能。
原则:1、不能修改被装饰的函数的源代码。
2、不能修改被装饰的函数的调用方式,调用还是用原函数名加(),但附加功能在里面。
高阶函数+嵌套函数==》装饰器
函数即变量。嵌套函数:在一个函数的函数体内,声明一个函数,而不是调用一个函数。
#example: import time def pisiwace(func): def deco(*args,**kwargs): 'coefficient correction' # args[0]+=2 # args[1]=args[1]*2 # args[2]+=1 time_start=time.time() func(*args,**kwargs) time_end=time.time() print('Interval time: %s '%(time_end-time_start)) return deco @pisiwace#test1=pisiwace(test1) def test1(x,y=2): "calculation" y=x**2+x*y time.sleep(2) print(x,y) return x,y @pisiwace#test2=pisiwace(test2) def test2(x,y,z): "calculation" y=x**2+x*y+z time.sleep(3) print(x,y,z) return x,y test1(2) test2(1,2,3)
当有多个装饰器本身存在参数时,可用多个函数嵌套。@login('remote')#home=login('remote')(home)
#example usename,password='wulihui',123456 def login(choise): if choise=='local': def option(func): def wrapper(x): _usename=input('usename:') _password=int(input('password:')) print(x) if usename==_usename and password==_password: source=func() return source else: print('invalid username or password') return wrapper return option elif choise=='remote': print('remote login connectting') def remote_login(x): 'remote login' return x return remote_login def _index(): 'index page' print('welcome to index page') return 'from index' @login('remote')#home=login('remote')(home) def home(): 'home page' print('welcome to home page') return 'from home' @login('local')#bbs=login(‘local’)(bbs) def bbs(): 'bbs page' print('welcome to bbs page') return 'from bbs' print(_index()) print(home()) print(bbs(3))
生成器:生成器一边循环,一边计算,生成器只有在调用的时候才能生成数据,比较节省内存。
#列表生成式
a=[i*3 for i in range(1,11,2)] print(a)
#生成器
gen1=(i*3 for i in range(1,11,2) )#定义生成器gen1 print(gen1.__next__())#取生成器中当前位置的下一个生成值,无法回到前一个值,只能逐个往后取 print(gen1.__next__()) print(gen1.__next__())
#循环调用
for i in gen1: print(i) # def fib(nmb):#这是函数 # n,a,b=0,0,1 # while n<nmb: # print(b) # a,b=b,a+b # n+=1 # return 'done' # fib(10)
元组知识补充
a,b=1,2#a=1,b=2,类似(a,b)=(1,2) a,b=b,a+b#此时先计算元组tuple=(a,a+b)=(2,1+2)=(2,3),再赋值,a=tuple[0],b=tuple[1] print(a,b)
#函数式生成器
def fib(nmb): n,a,b=0,0,1 while n<nmb: yield b#此时feb(nmb)为一个生成器,返回当前值,保留函数的中断状态 #print(b) a,b=b,a+b#含义参照tuple_knowledge.py n+=1 return 'done' #print(feb(10)) gen2=fib(10) print(gen2.__next__()) print(''.center(50,'-'))#中间可以插入其他操作 print(gen2.__next__()) print(gen2.__next__()) print(gen2.__next__()) print(gen2.__next__()) print(gen2.__next__()) print(gen2.__next__()) print(gen2.__next__()) print(gen2.__next__()) print(gen2.__next__()) print(gen2.__next__()) print(gen2.__next__())#next次数超过10会报错,报的为return的值 # #异常 # g=fib(10) # while True: # try: # x=next(g) # print('g:',x) # except StopIteration as e: # print('generator return value:',e.value) # break
#生成器协程处理
import time def consumer(name): 'consumer generator' print('consumer %s is coming'%name) while True: baozi=yield print('steamed stuffed bun %s is coming .And it is eat by %s.'%(baozi,name)) return 'coming' def productor(): 'productor generator' c1=consumer('A') c1.__next__() c2=consumer('B') c2.__next__() print('we have prepared steamed stuffed bun') baozi_list=['肉包','菜包','花卷','糖包','灌汤包'] for i in baozi_list: print('包子做好了') c1.send(i) c2.send(i) time.sleep(1) return 'done' productor() #判断是否可循环 from collections import Iterable gen1=consumer('op') print(isinstance(gen1,Iterable))
迭代器:
可迭代对象:可直接作用于for循环的对象,称为可迭代对象
判断是否为可迭代对象方法:
from collections import Iterable print(isinstance([1,2],Iterable))
可以被next()函数调用,并不断返回下一个值的对象,称为迭代器对象:Iterator
#判断是否为迭代器对象
from collections import Iterator print(isinstance((i+2 for i in range(10)),Iterator)) print(isinstance([i+2 for i in range(10)],Iterator))
#iter(o),将list、dict、set、str变成可迭代对象
print(isinstance(iter([1,2]),Iterator))
迭代器原理:
for i in [1,2,3,4]: pass #原理如下 it=iter([1,2,3,4]) while True: try: #获得下一个值 x=next(it) except StopIteration: #遇到StopIteration就退出循环 break
计算时间间隔的函数
import time def time_count(): time_start=time.time() time.sleep(1.5) time_end=time.time() print('time count is %s'%(time_end-time_start)) time_count()
匿名函数
def sayhi(n): print(n) sayhi(3) #改成匿名函数,即没有def sayhai=lambda n:print(n) sayhi(2) anonymous=lambda x:x*2 print(anonymous(4))
内置函数:
内置函数也叫内置方法。