簡體   English   中英

Python:帶有包裝器的裝飾器行為

[英]Python: behaviour of decorator with wrapper

我不明白為什么僅在我第一次調用函數multiple(x,y)時才執行“ cache = {}”行。 之后,該行將被忽略。 這使程序運行良好,但是我不了解這種行為。

def memoize(func):

     cache = {}
     print("cache")

     @functools.wraps(func)
     def wrapper(*args):
         if args in cache:
             return cache[args]

         result = func(*args)
         cache[args] = result

         return result

     return wrapper

 @memoize
 def multiply(x, y):
     return x * y

 print(multiply(2, 3))
 print(multiply(2, 3))

結果是:

 cache
 6
 6

因此,“ cache = {}”和“ print(“ cache”)“行僅在第一時間執行。 謝謝

裝飾器代碼的“每次執行”部分是包裝函數。 包裝函數外的代碼僅在應用運算符時執行-

這什么都不是魔術或“新的”-只看事物的順序和什么時候被稱為-正常執行順序中唯一不能被稱為魔術的東西就是裝飾本身-請記住:

 @memoize
 def multiply(x, y):
     return x * y

與以下內容相同:

def multiply(x, y):
     return x * y

multiply = memoize(multiply)

另外,如果您想了解裝飾器,請functools.wraps不要使用functools.wraps調用。 這對生產代碼和填入小細節都很有好處:它將包裝器函數偽裝成裝飾的內部函數(例如,在此示例中, multiply wrapper __name__屬性設置為multiply ),但是在嘗試時是不必要的復雜化了解裝飾者。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM