我正在阅读python装饰器,发现它们非常有用,但我有一个困惑,我试图在谷歌和stackoverflow上搜索,但没有找到好的答案,其中一个问题已经在stackoverflow上被问到了相同的标题,但那个问题谈到了@wrap,而我的问题是不同的:
那么什么是基本的装饰器模板:
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所以每当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那么包装器在装饰器中的用途是什么呢?
发布于 2017-09-11 09:06:50
这里有一个问题可能对你有所帮助。让我们更改new_func,以便它实际使用它传递的参数。例如:
def new_func(r):
print("new_func r:", r)假设我们有一个向new_func传递参数的another_func
def another_func():
new_func(999)对于您来说,问题是,如何编写deco才能
无论从another_func传递给
another_func的值是什么,andnew_func都会在没有任何更改的情况下继续工作https://stackoverflow.com/questions/46146829
复制相似问题