簡體   English   中英

為什么調用Python時不執行包裝函數?

[英]Why doesn't wrap function in Python get executed when I call it?

我有這個簡單的代碼。

def decor(func):
  def wrap():
    print("============")
    func()
    print("============")
  return wrap

def print_text():
  print("Hello world!")

decor(print_text())

為什么只打印“ Hello world!” 而不是兩個包裝?

在這里,您正在評估print_text (因此打印“ Hello World!”),並將結果傳遞給decor

decor(print_text())

在這里,我們將print_text傳遞給decor ,並調用返回的結果函數,即wrap ::

decor(print_text)()

注意,第一種情況不會調用decor返回的函數。 嘗試調用它,看看會發生什么:

decor(print_text())()

TypeError:“ NoneType”對象不可調用

因為func現在是None

那是因為您只返回函數wrap-不被調用。 如果確實要調用它,則可以將結果分配給變量,也可以直接使用decor(print_text)() 請注意,您應該使用print_text而不是print_text() ,因為后者將使函數的結果進行print_text() ,而不是函數本身。 工作版本為:

def decor(func):
  def wrap():
    print("============")
    func()
    print("============")
  return wrap

def print_text():
  print "Hello world!"

wrapped_function = decor(print_text)
wrapped_function()

您正在用單個參數調用decor 該參數是print_text()返回的值。 好吧, print_text()打印一些內容,然后返回None。 到目前為止,您的輸出僅僅是Hello world! 現在沒有任何內容傳遞給decor ,它返回wrap()函數。 wrap()實際上沒有調用,您的最終輸出就是Hello world!

您誤解了裝飾器的使用。 正確的語法是這樣的:

@decor
def print_text():
    print("Hello world!")

這是一個捷徑:

def print_text():
    print("Hello world!")

print_text = decor(print_text)

現在,您可以看到正在調用decor(print_text)wrap()函數)的返回,並且所有內容decor(print_text)打印。

暫無
暫無

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

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