【问题标题】:Why we use wrapper in decorator , when we can create decorator without wrapper?当我们可以在没有包装器的情况下创建装饰器时,为什么我们在装饰器中使用包装器?
【发布时间】: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


【解决方案1】:

这是一个可能有帮助的问题。让我们更改 new_func 以便它 实际上使用它传递的参数。例如

def new_func(r):
    print("new_func r:", r)

假设我们还有another_func,它将一个参数传递给new_func

def another_func():
    new_func(999)

你的问题是,你怎么能写deco这样

  • another_func 继续工作,没有任何变化,并且
  • new_func 接收从 another_func 传递给它的任何值

?

【讨论】:

    猜你喜欢
    • 2018-01-02
    • 2021-03-12
    • 2010-09-21
    • 1970-01-01
    • 2019-01-18
    • 2011-01-02
    • 2020-12-10
    • 2018-04-17
    相关资源
    最近更新 更多