python - @Python 中的装饰器 : why the inner defined function?

标签 python decorator

<分区>

我刚刚开始使用 Python,并且刚刚接触过装饰器。我编写了以下代码,模仿我所看到的,并且它有效:

def decorator_function(passed_function):
    def inner_decorator():
        print('this happens before')
        passed_function()
        print('this happens after')
    return inner_decorator

@decorator_function
def what_we_call():
    print('The actual function we called.')

what_we_call()

但后来我写了这个,它抛出了错误:

def decorator_function(passed_function):
    print('this happens before')
    passed_function()
    print('this happens after')

@decorator_function
def what_we_call():
    print('The actual function we called.')

what_we_call()

那么,为什么我们需要在装饰器函数中包含内部嵌套函数?它有什么作用?只使用第二个语法不是更简单吗?我没有得到什么?

有趣的是两者都有相同的(正确的)输出,但第二个也有错误文本,说“TypeError: 'NoneType' object is not callable”

请使用适合刚开始使用 Python 的人的语言和示例,Python 是他的第一门编程语言,也是 OOP 的新手! :) 谢谢。

最佳答案

原因是当您通过以下方式将 what_we_call 包装在 decorator_function 中时:

@decorator_function
def what_we_call():
    ...

你正在做的是:

what_we_call = decorator_function(what_we_call)

在你的第一个例子中,它起作用是因为你实际上没有运行 inner_function,你只是初始化它,然后你返回新的 inner_function(你稍后会在调用修饰的 what_we_call 时调用):

def decorator_function(passed_function):
    def inner_decorator():
        print('this happens before')
        passed_function()
        print('this happens after')
    return inner_decorator

相反,在您的第二个示例中,您将运行 2 个打印语句和中间的 passed_function(在我们的例子中是 what_we_call):

def decorator_function(passed_function):
    print('this happens before')
    passed_function()
    print('this happens after')

换句话说,您不返回之前示例中的函数:

what_we_call = decorator_function(what_we_call)

您运行代码(并看到输出),但随后 decorator_function 将“None”返回给 what_we_call(覆盖原始函数),当您调用“None”时,就好像它是 Python 提示的函数一样。

关于python - @Python 中的装饰器 : why the inner defined function?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32193218/

相关文章:

c# - 如何从外到内用 Ninject 绑定(bind)装饰器?

python - 如何将 pandas 中的格式应用到导出的 Excel 文件(特别是尝试填充空白单元格)

python - requests.get() 的执行时间非常长

python - 使用 Python 将 Geojson 转为 shapefile

python - 修饰递归函数

python - 装饰器 - 在 Python 中抛出无效语法

python - 可以用装饰器劫持类定义吗?

Python 多线程和 PostgreSQL

python - 如何保存Django ModelForm数据?

python - 如何在 Django 中使用装饰器保存发布数据