我正在用 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/