簡體   English   中英

Python 裝飾器正在吐出 無

[英]Python Decorator is spitting out None

我在 python 中學習了一些新主題,我終於接觸到了裝飾器,這看起來很酷,除了一個主要問題。 下面是我運行的代碼:

def new_dec(ori_func):
    def WrapFunc():
        print("First Line")
        ori_func()
        print("Second line")
    return WrapFunc

def new_func():
    print("This is the new function")

ThisFunc = new_dec(new_func)
print(ThisFunc())

但是,當執行此代碼時,它會輸出:

First Line
This is the new function
Second line
None

而且我不記得添加了 None 語句,這可能是已添加的類型變量嗎? 為什么會發生這種情況,以及如何解決。

您有四個打印語句。 所以打印了四件事。 默認情況下, function 返回None

>>> def f(): pass
>>> print(f())
None

檢查如果您定義會發生什么:

def new_dec(ori_func):
    def WrapFunc():
        print("First Line")
        ori_func()
        print("Second line")
        return "Fourth Line"
    return WrapFunc

或者,您可以刪除第四個打印:

# print(ThisFunc())
ThisFunc()

默認情況下,function 返回 None。 您只需致電 function 即可獲得您所期望的。

def new_dec(ori_func):
    def WrapFunc():
        print("First Line")
        ori_func()
        print("Second line")
    return WrapFunc

def new_func():
    print("This is the new function")

ThisFunc = new_dec(new_func)
ThisFunc() # get rid of the print statement

暫無
暫無

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

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