【发布时间】:2018-02-19 04:07:16
【问题描述】:
我正在阅读 python 装饰器,发现它们非常有用,但我有一个困惑,我试图在 google 和 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
那么装饰器中的包装器有什么用?
【问题讨论】:
-
print(wow(12))和print(wow)之间存在差异...在第二种情况下,您甚至无法返回函数。 -
有区别。第一种方法是返回函数,第二种方法是什么都不返回。只需在两次通话后添加
print(type(wow)),您就会看到它。
标签: python python-2.7 python-3.x closures decorator