【问题标题】:Why do wrapper functions need to be returned (decorators in python)为什么需要返回包装函数(python中的装饰器)
【发布时间】:2018-11-20 07:23:30
【问题描述】:

谁能解释一下为什么需要返回装饰器中的包装函数以及为什么

def decorate(func):
    def wrapper():
        print("Text")
        test_function()

@decorate
def test_function():
  print("More text")

test_function()

产生 NoneType 对象是不可调用的,而不是

def decorate(func):
    def wrapper():
        print("Text")
        test_function()
    return wrapper

@decorate
def test_function():
    print("More text")

test_function()

【问题讨论】:

  • 您的第二个代码块“永远”递归(直到它达到解释器的递归限制并引发异常),因为当wrapper 函数按名称调用test_function 时,它实际上是在调用自己。由于装饰器语法,原来的 test_function 被包装器取代。如果你想访问原始函数,你应该使用作为参数传递给装饰器的引用(即func)。还值得注意的是,您不需要在装饰器中使用包装函数。如果需要,您可以返回传递给您的相同函数。

标签: python decorator wrapper


【解决方案1】:

因为

@decorator
def f():
    ...

完全等价于

def f():
    ...
f = decorator(f)

所以decorator 必须返回一些东西才有意义,否则f 将是None

【讨论】:

    猜你喜欢
    • 2018-01-02
    • 2021-07-25
    • 1970-01-01
    • 2020-06-22
    • 2012-03-22
    • 1970-01-01
    • 2010-09-21
    • 2020-02-03
    相关资源
    最近更新 更多