1.装饰器
1)本质就是函数,(装饰其他函数),为其他函数添加附加功能
2)原则:
1.不能修改被装饰的函数源代码
2.不能修改被装饰的函数的调用方式
实现装饰器知识储备:
1.函数即”变量“
2.高阶函数
3.嵌套函数
高阶函数+嵌套函数=装饰器
案列一
import time
def trrm(fuc): #trrm(test1)
def cod(*args,**kwargs):
start_time=time.time()
fuc(*args,**kwargs) #run test1()
stop_time=time.time()
print('the fuc run is %s' %(stop_time-start_time))
return cod
@trrm
def test1():
time.sleep(3)
print('the is test1')
@trrm
def test2():
time.sleep(3)
print('the is test2')
test1()
test2()
>>>>>
the is test1
the fuc run is 3.0005998611450195
the is test2
the fuc run is 3.007200002670288
案列二
username,passwd = 'aron',123456
def verification(auth_type):
def wrrit(fuck):
def verifi(*args,**kwargs):
if auth_type == "local":
usernames = input("please enter user name:").strip()
passworld = int(input("please enter passworld:"))
if username == usernames and passwd == passworld:
fuck(*args,**kwargs)
else:
exit()
elif auth_type == "yuanc":
exit("不会")
return verifi
return wrrit
def index():
print("welcome to index page")
@verification(auth_type="local")
def home():
print("welcome to home page")
@verification(auth_type="yuanc")
def bbs(arg1):
print("welcome to %s page" %(arg1))
index()
home()
bbs(5)
>>>>>
welcome to index page
please enter user name:aron
please enter passworld:123456
不会
welcome to home page
Process finished with exit code 1
浙公网安备 33010602011771号