What does `@` mean in Python?

2020-04-11 06:13发布

What does @ mean in Python?

Example: @login_required, etc.

标签: python syntax
6条回答
男人必须洒脱
2楼-- · 2020-04-11 06:45

A decorator, also called pie syntax. It allows you to "decorate" a function with another function. You already had decoration with staticmethod() and classmethod(). The pie syntax makes it more easy to access and extend.

查看更多
姐就是有狂的资本
3楼-- · 2020-04-11 06:49

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.

查看更多
够拽才男人
4楼-- · 2020-04-11 06:51

That specific decorator looks like it comes from Django.

It might help you get a better understanding by reading the Django documentation about that decorator.

查看更多
闹够了就滚
7楼-- · 2020-04-11 07:06

If you ask this type of question you will probably be interested in the other hidden features of Python.

查看更多
登录 后发表回答