本質上,裝飾器就是返回乙個函式的高階函式。裝飾器就是乙個函式
裝飾器的原則:
函式即變數:
在python中,乙個變數首先被定義,分配記憶體空間,然後再使用。
以x=1,這個簡單的賦值語句為例子。首先在記憶體中分配乙個空間,x指向該記憶體空間,該記憶體空間記憶體入「1」
函式名本質也是乙個變數,所以def test()這個語句執行後,就是在記憶體中分配乙個空間,test指向該記憶體,該記憶體中存入函式體
**示例:
#author:yueru sun特別需要注意示例三是可以執行成功的,」示例三「=」示例二「#函式即變數
#示範一:
def foo():
print('in the foo')
foo()
#示範二:
def bar():
print('in the bar')
def foo():
print('in the foo')
bar()
foo()
#示範三:
#變數在使用的時候是先定義再使用
def foo():
print('in the foo')
bar()
def bar():
print('in the bar')
foo()
#示範四:
# def foo():
# print('in the foo')
# bar()
#foo()#報錯,因為此時bar還沒有定義
# def bar():
# print('in the bar')
因為在foo()執行,首先是def 了foo()和bar(),所以當執行到foo()的時候可以找到foo()和bar()
示例四是不可以執行的。因為在foo()執行之前,bar還沒有在記憶體中定義,找不到
高階函式:
高階函式就是滿足函式當作引數被傳遞或者函式的返回值是函式
巢狀函式:
def f1():還是從函式就是乙個變數這個角度解釋,因為f3()是在f1()內部定義的,相當於是」區域性變數「,所以不能在函式外部訪問到f3()def f2():
def f3():
print('from f3')
f3()
f2()
f1()
f3() #報錯,為何?請看下一小節
import time上面的**解釋:def timer(func): #timer(test1) func=test1
def deco(*args,**kwargs):
start_time=time.time()
func(*args,**kwargs) #run test1()
stop_time = time.time()
print("the func run time is %s" %(stop_time-start_time))
return deco
@timer #test1=timer(test1)
def test1():
time.sleep(1)
print('in the test1')
test1()
#執行結果:
#in the test1
#the func run time is 1.0033304691314697
函式timer最本質的作用就是返回乙個deco,deco是乙個函式的位址空間
接下來需要理解的是@timer等價於:test1=timer(test1),timer(test1)執行之後就會返回deco,那執行test1就相當於執行了deco,即test1()=deco()
所以test1()的結果是:
in the test1
the func run time is 1.0033304691314697
再來乙個例子:
author:yueru sun還是上面的理解過程,梳理一下執行過程:import time
def timmer(func):
start_time=time.time()
func(*args,**kwargs)
end_time=time.time()
print('func 的 執行時間是:%s'%(end_time-start_time))
@timmer
def test():
time.sleep(2)
print('test')
test()
@timmer
def test1(number):
time.sleep(1)
print('func的第%s執行'%(number))
test1(1)
首先是定義了timer函式,接下來執行@timer就等價於執行test1=timer(test1),執行完返回了deco,那麼test1(number)=deco(number)
如果裝飾器需要傳入引數,那麼就在上面的基礎上再巢狀一次函式
def timmer1(text):具體的理解不贅述了,可以複習一下這個文章:start_time=time.time()
func(*args,**kwargs)
end_time=time.time()
print('%s func 的執行時間是%s'%(text,end_time-start_time))
@timmer1('sun')
def test2():
print('test2')
test2()
編寫裝飾器,為多個函式加上認證的功能(使用者的賬號密碼**於檔案),要求登入成功一次,後續的函式都無需再輸入使用者名稱和密碼
Python之裝飾器學習筆記
裝飾器本質上是乙個python函式,其返回值也是乙個函式物件 作用 不修改原函式情況下,為已有函式新增新的功能。如插入日誌 效能測試 事務處理 快取 許可權校驗等場景。閉包函式 在函式內部定義乙個內嵌函式,內嵌函式引用了外部函式的變數,此時內嵌函式稱為閉包函式。閉包函式所引用的外部定義的變數被叫做自...
python學習筆記之裝飾器
def print msg print msg是外函式 msg i m 狂師 defprinter printer是巢狀函式 print msg return printer 返回巢狀函式printerdef func a,b def line n nonlocal a nonlocal用於宣告變數...
Python之裝飾器筆記
概述 用於管理和增強函式和類行為的 提供一種在函式或類定義中插入自動執行 的機制 特點 更明確的語法 更高的 可維護性 更好的一致性 編寫函式基礎 將函式賦給變數 將函式作為引數傳遞 函式巢狀及跨域訪問 函式定義裝飾器 通用性更好 1 函式定義裝飾器 2 通用性更好34 引數化裝飾器 5def ta...