@ Modifier -- decorator in python, modifier -- python Decoration

Source: Internet
Author: User

@ Modifier -- decorator in python, modifier -- python Decoration

Http://blog.csdn.net/shangzhihaohao/article/details/6928808

The decorator mode allows you to dynamically and transparently add responsibilities to a single object without affecting other objects, and also process the revoking responsibilities. It is often used for logging and performance testing.

Imagine this very common scenario. You wrote a method to provide access only to login users (in fact, I learned @ modifier through django @ login_required ), you can write the following code:


Of course there is no problem with this, but you have written Method B, which requires that only login users can access it, so you have written the following code:

 

def B():    if user.is_login():        do something    else:        pass

 

The problem arises. You are copying and pasting. If there are not two methods but a bunch of methods, you may not be able to stand it. Of course, if you are smart, you can come up with this method:

def A():    passdef B():    passdef login_required(fn):    def ff():        if user.is_login():            fn()        else:            pass    return ffA = login_required(A)B = login_required(B)

 

You may not have imagined that the elegant support of python for such a useful thing is the @ modifier.

def login_required(fn):    def ff():        if user.is_login():            fn()        else:            pass    return ff@login_requireddef A():    pass@login_requireddef B():    pass

 

Write A @ Modifier on method A. When method A is called, Method B following the modifier is called. Method B takes method A as A parameter, in addition, A callable object needs to be returned. This callable object will be executed using the parameters provided by method. Let's look at this example:

#!/usr/bin/env pythondef a(fn):    print 'a'    def d(st):        print st+'d'    return ddef b(fn):    print 'b'    return fn@a@bdef c(st):    print st    c('c')

 

Output result: bacd

When we call c ('C'), we will first call B (c), B (c) to print the character "B" and then return c, and then call a (c ), a (c) prints the character "a", returns method d, and then executes d ('C') to print the cd.


@ Is in python

Modifier, such
Class:
@ Staticmethod
Def m (self ):
Pass
It is equivalent
Class:
Def m (self ):
Pass
M = staticmethod (m)
Actually, it is to call a function parameter as the downstream variable and replace it.

How should I understand the python decorator?

The so-called decorator is to wrap the function and add some additional functions for the function. The decorator is a function. The parameter is the encapsulated function and the encapsulated function is returned: You can try again:
Def d (fp): def _ d (* arg, ** karg): print "do something before fp .. "r = fp (* arg, ** karg) print" do something after fp .. "return r return _ d @ ddef f (): print" call f "# The above @ d is used to indicate the decorator and the following: # f = d (f) f () # Call f

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.