ARTICLE DETAIL

资讯详情

深耕网站建设与运营推广的一线实战洞察。

装饰器decorator总结(函数即是变量、高阶函数、嵌套函数、参数组)

装饰器decorator总结(函数即是变量、高阶函数、嵌套函数、参数组) 装饰器decorator的本质他就是函数原则–对于被装饰的函数他不发生任何变化他是透明的。不能修改被装饰的函数的源代码不能修改被装饰的函数的调用方式函数就是”变量“普通变量。先定义后使用如x1先定义变量x和再调用变量函数也如此先定义函数在调用函数#第一步定义deffibo(x):ifx0:return1elifx1:return1else:returnfibo(x-1)fibo(x-2)#第二步调用print(fibo(10))存储也是一样函数名以及函数体存储普通变量x为名牌号1为值存储在内存中函数则函数名为名牌号函数体存储在内存中匿名函数特殊的匿名函数没有函数名用完即回收lambda x :print(x)高阶函数如def test(x,y,func)把一个函数当做参数传参给另外一个函数返回值包含函数名defsum(a,b,c):returnabc#sum是函数名为传参deffun(a,b,c,sum):print(count:)returnsum(a,b,c)#返回值sum函数名print(fun(1,2,3,sum))函数嵌套:定义函数时函数中包含另外一个函数。deffoo():print(in the foo)defbar():#函数foo中的函数print(in the bar)bar()foo()装饰器高阶函数嵌套函数defdecorator(func):#func_test01传值给func 高阶函数defwrapper(*args,**kwargs):#嵌套函数 参数组start_timetime.time()func(*args,**kwargs)#调用func_test01 参数组stop_timetime.time()print(the fun runtime is {}.format(stop_time-start_time))returnwrapper#返回这个函数的内存地址decorator#func_test01decorator(func_testo1)deffun_test01():#原函数的源代码不变time.sleep(1)print(in fun_test01)fun_test01()#函数调用方式不变带参数组的装饰器三层嵌套importtime user_nameaganpassword123defauth(auth_type):defouter_wrapper(func):print(you auth_type is {}.format(auth_type))defwrapper(*args,**kwargs):print(wrapper func args:,*args,**kwargs)ifauth_typelocal:unameinput(Please input your username: ).strip()#去掉字符串开头和结尾的空白字符psdinput(Please input your password: ).strip()ifunameuser_nameandpsdpassword:print(you have authenticated!)resfunc(*args,**kwargs)# 调用funcreturnreselse:print(wrong username or password!)else:print(wrong auth type!)returnwrapperreturnouter_wrapperdefindex():print(welcome to index page)auth(auth_typelocal)# home outer_wrapperdefhome():print(welcome to home page)index()home()
返回列表