Python 为什么我们在decorator中使用包装器,而我们可以创建没有包装器的decorator?
我正在阅读python decorators,发现它们非常有用,但我有一个困惑,我试图在google和stackoverflow上搜索,但没有找到好的答案,在stackoverflow上已经有一个问题以相同的标题提出,但该问题涉及@wrap,我的问题不同: 那么什么是基本的装饰模板是:Python 为什么我们在decorator中使用包装器,而我们可以创建没有包装器的decorator?,python,python-2.7,python-3.x,closures,decorator,Python,Python 2.7,Python 3.x,Closures,Decorator,我正在阅读python decorators,发现它们非常有用,但我有一个困惑,我试图在google和stackoverflow上搜索,但没有找到好的答案,在stackoverflow上已经有一个问题以相同的标题提出,但该问题涉及@wrap,我的问题不同: 那么什么是基本的装饰模板是: def deco(x): def wrapper(xx): print("before the deco") x(xx) print("after the
def deco(x):
def wrapper(xx):
print("before the deco")
x(xx)
print("after the deco")
return wrapper
def new_func(a):
print("this is new function")
wow=deco(new_func)
print(wow(12))
其结果是:
before the deco
this is new function
after the deco
None
before the deco
this is new function
after the deco
None
所以每当deco返回它调用包装器函数时,现在我不明白为什么我们使用包装器,而我们的主要目标是将new_func作为参数传递给deco函数,然后在deco函数中调用该参数,如果我尝试,那么我可以在这里创建相同的东西,而不使用包装器函数:
def deco(x):
print("before the deco")
a=1
x(a)
print("after the deco")
def new_func(r):
print("this is new function")
wow=deco(new_func)
print(wow)
其结果是:
before the deco
this is new function
after the deco
None
before the deco
this is new function
after the deco
None
那么包装器在decorator中有什么用途呢 这里有一个问题可能会有所帮助。让我们将
new_func
更改为
实际上使用它传递的参数。e、 g
def new_func(r):
print("new_func r:", r)
假设我们还有另一个函数
,它将一个参数传递给新函数
:
def another_func():
new_func(999)
你的问题是,你如何编写deco
,使
继续工作,没有任何更改和另一个_func
接收从另一个\u funcnew\u func
print(wow(12))
和print(wow)
之间有区别。。。在第二种情况下,你甚至没有得到一个函数,这是有区别的。第一种方法是返回函数,第二种方法是不返回任何内容。只需在两次通话后添加print(键入(wow))
,您就会看到它。