【发布时间】:2019-02-24 09:00:18
【问题描述】:
我正在用 Python 阅读这段代码 sn-p:
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,上面的代码 sn-p 将产生相同的结果,无论我们是否有这行 return result。
我想知道是否有任何理由(Pythonic?未来的代码维护?)返回这个 None。
代码 sn-p 是 YouTube 上关于装饰器的 Python 教程的一部分。
谢谢
【问题讨论】:
-
你原来的函数
display_info返回None,因为它没有return语句。这与装饰器无关。修饰后的版本返回result,这是原始函数的返回值,即None。如果使用相同的装饰器来装饰一个不同的函数(一个返回值的函数),它就会有不同的返回值。 -
@khelwood,谢谢我在原来的帖子中犯了一个错误。我想问的是:为什么我们有返回结果,而不是打印(结果)。
-
你应该使用
#在 python 中启动内联 cmets 而不是// -
@Mohit,谢谢。已更正
标签: python return return-value python-decorators