为什么需要返回包装函数(python中的装饰器)

时间:2018-06-11 05:34:48

标签: python decorator wrapper

有人可以解释为什么需要返回装饰器中的包装器函数以及为什么

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()

1 个答案:

答案 0 :(得分:2)

由于

@decorator
def f():
    ...

完全等同于

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

所以decorator必须返回一些有意义的内容,否则f将为None