deffoo():print('in the foo')defbar():#函数foo中的函数print('in the bar')bar()foo()
装饰器=高阶函数+嵌套函数
defdecorator(func):#func_test01传值给func 高阶函数defwrapper(*args,**kwargs):#嵌套函数 参数组start_time=time.time()func(*args,**kwargs)#调用func_test01 参数组stop_time=time.time()print("the fun runtime is {}".format(stop_time-start_time))returnwrapper#返回这个函数的内存地址@decorator#func_test01=decorator(func_testo1)deffun_test01():#原函数的源代码不变time.sleep(1)print('in fun_test01')fun_test01()#函数调用方式不变
带参数组的装饰器:三层嵌套
importtime user_name="agan"password="123"defauth(auth_type):defouter_wrapper(func):print("you auth_type is {}".format(auth_type))defwrapper(*args,**kwargs):print('wrapper func args:',*args,**kwargs)ifauth_type=='local':uname=input("Please input your username: ").strip()#去掉字符串开头和结尾的空白字符psd=input("Please input your password: ").strip()ifuname==user_nameandpsd==password:print("you have authenticated!")res=func(*args,**kwargs)# 调用funcreturnreselse:print("wrong username or password!")else:print("wrong auth type!")returnwrapperreturnouter_wrapperdefindex():print("welcome to index page")@auth(auth_type="local")# home = outer_wrapperdefhome():print("welcome to home page")index()home()