python - Python 3 中函数前面的 '@' 是什么意思?

标签 python django python-3.x

我搜索了@的含义当它出现在 Python 中的函数之前时,我找不到有用的东西。

例如,我在 Django 中看到了这段代码:

@login_required

...这在 goto-statement 包中:

@with_goto

这是什么意思?

最佳答案

它代表装饰器。装饰器是一个函数,它接受另一个函数并扩展后一个函数的行为,而无需显式修改它。

def decorator_function(func):
    def inner_function():
        print("Before the function is called.")
        func()
        print("After the function is called.")
    return inner_function

@decorator_function
def args_funtion():
    print("In the middle we are!")

实际上这个@decorator_function装饰器执行与以下相同的工作:

args_funtion = decorator_function(args_funtion)

现在如果你调用它,结果将是:

>>> args_funtion()
Before the function is called.
In the middle we are!
After the function is called.

关于python - Python 3 中函数前面的 '@' 是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60936950/

相关文章:

python - 如何解决溢出错误: math range error

python - 在 Python 3 中尾随小数点 >= 0.5 时,math.ceil() 和 round() 之间的算法有什么区别?

python - 如何使用生成器在 Python 中生成不带 "reverse duplicates"的列表排列

python - 在 Python 中使用 Rpy2 对齐 ggplot2 中不同的非小平面图

django - 完整性错误 : null value in column "email" violates not-null constraint

django - 要求某些字段不能全部留空。至少需要一个

python - 根据值过滤 pandas DataFrame 中的行

python生成xml

python - 如何在 Django 中按 `through` 表中的字段对 M2M 关系进行排序?

Python镜像字符串函数