我已经阅读了这两个问题的所有答案: Why do we need wrapper function in decorators? 和 Why are decorator functions designed in the way they are?,但我还是不明白。
为什么装饰器是这样写的:
def decorator_function(function):
def wrapper_function():
print('Before the decoration')
function()
print('After the decoration')
return wrapper_function
而不仅仅是这样:
def decorator_function(function):
print('Before the decoration')
function()
print('After the decoration')
return function
为什么我这样做:
@decorator_function
def original_function():
print('Original function')
在第一种情况下,使用包装函数,如果我像这样调用函数 original_function()
返回是:
Before the decoration
Original function
After the decoration
但是在第二种情况下,没有包装函数,如果我调用函数,结果是这样的:
Before the decoration
Original function
After the decoration
Original function
原函数又被调用一次
为什么我需要包装函数?
这似乎是一个愚蠢的问题,如果是这样,我深表歉意。但我真的很难理解它,尽管在这里搜索了互联网和其他问题。
提前致谢。