裝飾器: 本質是函式, 功能是為其他函式新增附加功能原則:1 不修改被修飾函式的源**
2 不修改被修飾函式的呼叫方式
為了實現裝飾器的功能,需要了解3個概念
1。高階函式
高階函式定義函式接收的引數是乙個函式名
函式的返回值是乙個函式名
滿足上述條件的任意乙個,都稱為高階函式
deffoo():
print('
from the foo')
deftest(func):
return
func
res = test(foo)
res()
函式test()就是高階函式, 因為其輸入的引數就是foo函式名, 返回的也是func指示的foo的函式名
需要指出的是:
res()實際上就是foo()
我可以把 res = test(foo) ==> foo = test(foo)
巢狀函式
指的是在函式內在建立乙個函式
deffather(name):
#print('from father%s' %name)
defson():
#print('我的爸爸是%s'%name)
defgrandson():
#name='就是我自己'
print('
my grandfather%s
'%name)
return
grandson
return
sonfather(
'abc
')()()#
my grandfather abc
執行一次函式返回內層巢狀函式的函式名在此執行(),又返回其內層的函式名再次執行(),把最內層的print出來
函式巢狀的目的很簡單:
把引數傳遞給最裡層的函式,並執行最裡層函式 --實際上就是閉包的概念
整個的裝飾器的原理和實現已經完成了!裝飾器的功能實現由4個內容的實現
1。執行被裝飾的函式
2。傳遞被裝飾函式的引數
3。返回被裝飾函式的返回值
4。 在語法糖上輸入各種可以傳入的引數,以實現功能的增強
importtime
deftimmer(func):
def inner(*args, **kwargs):
start_time =time.time()
res = func(*args, **kwargs)
stop_time =time.time()
print('
程式test執行時間%s
' % (stop_time -start_time))
return
res
return
inner
def test(name):
time.sleep(1)
print('%s
test is over
'%name
)
return true
以上就是裝飾器的簡單程式。 目前需要執行程式,為了實現裝飾的呼叫不變的要求
test =timmer(test)test()
需要分兩步走,第一步獲得inner函式的位址,賦值給test 然後執行test ,第二步執行test實際上是執行了inner函式, 在inner函式內的真實test的位址得到執行。
從而實現功能
把test =timmer (test ) ===> @ timmer來修飾test, 使得test () 更加真實還原!!!
importtime
deftimmer(func):
def inner(*args, **kwargs):
start_time =time.time()
res = func(*args, **kwargs)
stop_time =time.time()
print('
程式test執行時間%s
' % (stop_time -start_time))
return
res
return
inner
@timmer
#test = timmer(test)
def test(name):
time.sleep(1)
print('%s
test is over
'%name
)
return
true
test('alex')
執行結果:
alex test isover
程式test執行時間1.0000572204589844
裝飾器,高階函式,巢狀函式
裝飾器 本質是函式,裝飾其他函式 就是為其他函式新增其他功能 原則 1.不能修改被裝飾函式的源 2.不能修改被裝飾函式的呼叫方式 補充記憶體管理機制 函式即變數 匿名函式沒有名字,定義之後馬上被銷毀,除非賦值給乙個變數 def text1 print text1 text2 def text2 pr...
裝飾器 高階函式 閉包 函式巢狀
裝飾器 本質就是函式,作用是給其他函式新增新功能 1 不修改被修飾函式的源 2 不修改被修飾函式的呼叫方法 import time deftimmer func def args,kwargs start time time.time res func args,kwargs end time ti...
裝飾器2 高階函式 函式巢狀 閉包
高階函式定義 1.函式接受的引數是乙個函式名 2.函式的返回值是乙個函式名 3.滿足上訴條件任意乙個,都可稱之為高階函式 1 deftest 2print 你好啊 3 defhigh func func 4print 高階函式 5func 6high func test 7輸出 8高階函式 9 你好...