【发布时间】: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)。还值得注意的是,您不需要在装饰器中使用包装函数。如果需要,您可以返回传递给您的相同函数。