What does `@` mean in Python?

后端 未结 6 1617
盖世英雄少女心
盖世英雄少女心 2021-01-19 15:40

What does @ mean in Python?

Example: @login_required, etc.

6条回答
  •  粉色の甜心
    2021-01-19 16:10

    It is decorator syntax.

    A function definition may be wrapped by one or more decorator expressions. Decorator expressions are evaluated when the function is defined, in the scope that contains the function definition. The result must be a callable, which is invoked with the function object as the only argument. The returned value is bound to the function name instead of the function object. Multiple decorators are applied in nested fashion.

    So doing something like this:

    @login_required
    def my_function():
        pass
    

    Is just a fancy way of doing this:

    def my_function():
        pass
    my_function = login_required(my_function)
    

    For more, check out the documentation.

提交回复
热议问题