开发者

python lines that start with @ [duplicate]

开发者 https://www.devze.com 2023-03-20 10:48 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: Understanding Python decorators
This question already has answers here: Closed 11 years ago.

Possible Duplicate:

Understanding Python decorators

I was reading a django app source code where I find this

@login_required
def activities(request = None,\
            project_id = 0,\
          开发者_Go百科  task_id = 0,\
            ...

What does the line that start with @ mean?


It's a decorator. What it does is basically wrap the function. It is equivalent with this code:

def activities(request = None,\
            project_id = 0,\
            task_id = 0,\
            ...
activities = login_required(activities)

It is used for checking function arguments (in this case request.session), modifying arguments (it may give the function other arguments than it passes), and maybe some other stuff.


It's a decorator, which is a special type of function (or class, in some cases) in Python that modifies another function's behavior. See this article.

@decorator
def my_func():
    pass

is really just a special syntax for

def my_func():
    pass
my_func = decorator(my_func)


Please check out Python Decorators Explained. It has an amazing answer that will explain everything.


It is a decorator. It's a syntatic sugar for:

def activities(request = None,\
            project_id = 0,\
            task_id = 0,\
            ...

activities = login_required(activities)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号