python - 为什么我们在这个装饰器中返回 None ?

标签 python return return-value python-decorators

我正在用 Python 阅读此代码片段:

def decorator_function(original_function):
    def wrapper_function(*arg,**kwargs):
        print("This line is executed before the original function")
        result = original_function(*arg, **kwargs)
        print("This line is executed after the original function")
        print (result)
        return result #Why do we need to return result from this decorator?
    return wrapper_function

@decorator_function
def display_info(name, age):
    print(name, age)

display_info("You", 1)
display_info("Me", 99)

装饰函数返回一个 None,无论我们是否有这一行,上面的代码片段都会产生相同的结果,返回结果

我想知道是否有任何理由(Pythonic? future 的代码维护?)返回此 None。

该代码片段是 YouTube 上有关装饰器的 Python 教程的一部分。

谢谢

最佳答案

修饰函数将返回 None,因为函数 display_info 没有 return 语句,因此它返回 void。并且decorator_function内部的闭包返回并打印与调用原始函数display_info返回的值相同的值(它不受装饰器的操作影响),很明显它将返回一个 None 值。

编辑:

Why do we need that return statement?

在这种情况下,这是完全可选的,您确定这个装饰器只能添加到返回 void 或绝对不返回任何内容的函数中,但如果不是这种情况,您需要添加一个 return 语句,因为如果您不这样做不要添加 return 语句,您的原始函数有机会返回某些内容将返回 void。

关于python - 为什么我们在这个装饰器中返回 None ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54850322/

相关文章:

python - PyQt。显示操作系统进程?

可从类方法访问的python类变量?

python - PyGTK TreeView : Prevent last column from growing

python-selenium-chromedriver 没有启动任何可见窗口

c++ - 如何处理在 C/C++ 中返回的指向动态内存的指针

c++ - 用户定义的函数仅返回可能值中的 1 个

c++ - GCC 优化返回值

python - 如果 x 在多个列表中的任何一个中,我如何返回 True?

Go:从 defer 中返回

JAVA 返回对象或按引用传递