黑猴子的家 python 裝飾器之高階函式

2021-09-11 16:31:18 字數 1112 閱讀 6866

(1)把乙個函式名當做實參傳給另外乙個函式,在不修改被裝飾的函式源**的情況下

為其新增功能

(2)返回值中包含函式名,不修改函式的呼叫方式

code 情況1

import time

def bar():

time.sleep(3)

print('in the bar')

def t1(func):

#print(func)

start_time = time.time()

print("記憶體位址(門牌號)",func)

func()

stop_time = time.time()

print("the func tun time is %s" %(stop_time-start_time))

#列印記憶體位址

t1(bar)

列印

記憶體位址(門牌號) in the bar

the func tun time is 3.0

code 情況2

import time

def bar():

time.sleep(3)

print('in the bar')

def t2(func):

print(func)

return func

#加上括號是把返回值傳進去了 ,就不符合高階函式的定義了

#print(t2(bar()))

print(t2(bar))

#t2(bar())

t3 = t2(bar)

print(t3)

t3() # run bar

#高階函式 不修改函式的呼叫方式, 新增功能, 類似於隱士轉換 ,實現了裝飾器")

bar = t2(bar)

bar()

列印

in the bar

in the bar

黑猴子的家 python 裝飾器

裝飾器本質是函式,裝飾其他函式 就是為其他函式新增附加功能 1 不能修改被裝飾的函式的源 2 不能修改被裝飾的函式的呼叫方式 3 裝飾器對它被裝飾的韓式是完全透明的 1 函式即 變數 2 高階函式 3 巢狀函式code import time 裝飾器 def timmer func def warp...

黑猴子的家 python 裝飾器實現的迭代過程

code 高階函式 迭代裝飾器一 def deco func start time time.time func stop time time.time print the func run time is s stop time start time def deco1 func star tim...

黑猴子的家 Python 簡介

總的來說,程式語言各有千秋。c語言是可以用來編寫作業系統的貼近硬體的語言,所以,c語言適合開發那些追求執行速度 充分發揮硬體效能的程式。而python是用來編寫應用程式的高階程式語言。當你用一種語言開始作真正的軟體開發時,你除了編寫 外,還需要很多基本的已經寫好的現成的東西,來幫助你加快開發進度。比...