簡體   English   中英

python decorator如何在此代碼上工作?

[英]How does python decorator work on this code?

我試圖了解python裝飾器。 我以某種方式理解了裝飾器,直到編寫了這段代碼。

def func():
     def wrapper(x):
        return x()
     return wrapper 

@func()
def b():
    return sum

a = b([1,2,5])
print a # Result: 8 How?

e = b # pass b function to variable e
f = e([3,4,8]) # called function b stored in variable e
print f # Result: 15
# I understand how 15 is derived here

您使用func作為裝飾器工廠 ,該工廠產生了一個裝飾器,該裝飾器稱為原始b()來產生裝飾結果。 這是發生了什么:

  • @func()執行func() 第一 ,然后使用返回值作為裝飾。 func()返回wrapper ,因此將wrapper用作裝飾器。
  • wrapper(b)設置x = b並返回x() 因此,裝飾器的結果為b() ,即sum Python設置b = sum
  • 您調用了b([1, 2, 5]) ,其中b = sum 因此返回sum([1, 2, 5])

這里的重要部分是,您不是將func用作裝飾器,而是用作裝飾器工廠(稱其為實際的裝飾器),這增加了一個間接層。

暫無
暫無

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

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