1. 程式人生 > >Python之----裝飾器

Python之----裝飾器

-s 展示 裝飾 參數 nbsp func start 接下來 pytho

作用:

  在不改變函數源代碼的前提下,給函數增加新的功能。

裝飾器
1,本質上是一個函數
2,功能---裝飾其他函數(為其他函數添加其他功能)
3,不能修改被裝飾函數的源代碼
4,不能修改被裝飾函數的調用方式

實現裝飾器的知識儲備:
1,函數即“變量”
2,高階函數
a,把一個函數當作實參,傳給另外一個函數(在不修改被裝飾函數源代碼情況下,為其增加功能)
b,返回值包含函數名(不修改函數的調用方式)
例子:
def bar():
print("this is bar")
def test(func):
print("this is test")----看作是添加的新功能
return func--------------bar其實就是一個內存地址,加上()的時候就能調用。當把bar當作參數傳給test的時候,返回的就是bar內存地址。
bar = test(bar)-------------這個操作就相當於:即給了bar一個內存地址使其加上()能調用,且能將test函數裏的print內容展示出來
bar()
運行結果:
this is test
this is bar
3,嵌套函數
在函數內部def一個函數。
def test():
print("hahaha")
def bar():
print("bababa")
bar()
test()
運行結果:
hahaha
bababa

高階函數+嵌套函數 =>裝飾器

import time
def timer(func):
def dec(*args,**kwarge):#加上這兩個,是預防被裝飾的函數帶有參數。
start_time = time.time()
func(*args,**kwarge)#加上這兩個,是預防被裝飾的函數帶有參數。
end_time = time.time()
print("pro run time is %s"%(end_time-start_time))
return dec
@timer #等價於 test1 = timer(test1)。timer(test1)這個函數執行結果是返回了 dec的內存地址。-----高階函數知識點:返回值包含函數名
#其實就是相當於把dec對應的那個內存空間再多加了一個名字“test1”
#而原先的test1的內存空間當作一個參數,傳給了timer,並給了個名字func。-----高階函數知識點:把函數當作實參,傳給另外一個函數
def test1():
time.sleep(3)
print("this is test1")
def test2(name):
print("welecome %s"%name)
test1()#所以當執行到這一段的時候,其實是執行的dec(),然後接下來步驟就顯而易見了。
test2()

裝飾器自己也可以帶參數

Python之----裝飾器