What does the Python decorator mean? How do I use the python adorner?

Source: Internet
Author: User
Tags python decorator

Python---decorator detailed

Defined:

is essentially a function. The function is to decorate another function (that is, to be decorated function), to add functionality to the decorated function. The premise is that the source code and calling method of the decorated function cannot be changed. Such a function is called an adorner.

Analytical:

Below we say not much, directly with the code description. Here is a function.

      B=1+2

Program output:

————————

3

————————

Now I'm going to add an explanatory sentence to this function, as below, we can write an adorner:

1 #原函数 2 def Add (): 3     a=1+2 4     print (a)   5 #装饰器 6 def Decorator (func): 7     def warpper (): 8         print ("1+2 result is : ") 9         func ()     return warpper11 #注意此句   add=decorator (add) #调用函数14 Add ()

Program output:

——————————

The result of 1+2 is:

3

——————————

So that we can succeed in achieving our goal. Note here that the 12th line of this sentence, this is the Add function object passed in the decorator () function, the return is a new function variable, the new function object is re-assigned to add, so as to ensure that the function is not changed by the method of the call unchanged. There is a more elegant way to replace the 12th line of statements in the Python syntax. As follows:

1  #装饰器 2 def Decorator (func): 3     def warpper (): 4         print ("The result of 1+2 is:") 5         func () 6     return Warpper 7< C14/>8 #add =decorator (add) 9 #原函数10 @decorator # Change to the @ symbol def add ():     a=1+213     Print (a) #调用函数15 add ()

In front of the decoration function directly with "@xxx" (XXX for the adorner function name) can be

What happens if the decoration function has parameters ?

What if the adorner function has parameters? What's the class? Don't worry, we can collect parameters in the form of indefinite parameters. The instance code is as follows:

1 def Decorator (func): 2     def warpper (*args,**kwargs): 3         print ("The result of the addition is:") 4         func (*args,**kwargs) 5     Return Warpper 6  7 @decorator 8 def add (x, y): 9     a=x+y10     Print (a) Add (2,3)
Program output: The result of —————————————————— addition is: 5 ——————————————————

Below is a page validation decorator.

As you know, some of the sites are part of a page that requires users to log in before they can access them, such as the following three functions (representing three pages respectively):

1 def index (): 2     print ("Welcome to the Index page") 3 Def Home (): 4     print ("Welcome to the Home page") 5 def BBS (): 6< C13/>print ("Welcome to the BBS page") 7     return "I am the return contents"

If we want to add validation to the home page and BBS page now, obviously it is not feasible to change the source code now. This time we can use the adorner, as follows:

1 username,passwd= "Jack", "Abc123" #模拟一个已登录用户 2 def Decorator (func): 3     def warpper (*args,**kwargs): 4         username= Input ("Username:"). Strip () 5         password=input ("Password:"). Strip () 6         if Username==username and passwd== Password:7             Print ("Authenticate success!") 8             func (*args,**kwargs) 9         else:10             exit ("Username or Password is invalid! ")     return Warpper12 def index ():     print (" Welcome to the index page ") @decorator16 def Home ():     prin T ("Welcome to the Home page"), @decorator19 def BBS ():     print ("Welcome to the BBS page")     return "I am the RE Turn Contents "index () Home () BBS ()

Program results:

————————

Welcome to the index page #index页面未验证直接可以登入
Username:jack
Password:abc123
Authenticate success! #登录的而情形
Welcome to the Home page
Username:jack #密码或用户名错误的情形
Password:123
Username or password is invalid!
————————

We notice that BBS () has a return value, if we change the last sentence of the above code (line 25th) to "Print (BBS ())" and then look at his output:

————————

Welcome to the index page
Username:jack
Password:abc123
Authenticate success!
Welcome to the Home page
Username:jack
Password:abc123
Authenticate success!
Welcome to the BBS page
None #返回值能么成None了???

————————

What happened! The return value of BBS () is printed out to be none. How could that be? Does this change the source code of the decorated function? How can we solve it?

Let's analyze:

We execute the BBS function is equivalent to executing the wrapper function in the adorner, carefully analyzing the adorner found that the wrapper function has no return value, so in order to allow him to correctly ensure that the return value of the decorated function can be returned correctly, you need to modify the adorner:

1 username,passwd= "Jack", "Abc123" #模拟一个已登录用户 2 def Decorator (func): 3     def warpper (*args,**kwargs): 4         username= Input ("Username:"). Strip () 5         password=input ("Password:"). Strip () 6         if Username==username and passwd== Password:7             Print ("Authenticate success!") 8            return func (*args,**kwargs) #在这里加一个return就行了 9         else:10             Exit ("Username or password is invalid! ")     return Warpper12 def index ():     print (" Welcome to the index page ") @decorator16 def Home ():     prin T ("Welcome to the Home page"), @decorator19 def BBS ():     print ("Welcome to the BBS page")     return "I am the RE Turn Contents "index () Home () BBS ()

Plus the return of line 8th can be solved. Let's look at the program output after the change:

————————

Welcome to the index page
Username:jack
Password:abc123
Authenticate success!
Welcome to the Home page
Username:jack
Password:abc123
Authenticate success!
Welcome to the BBS page
I am The return contents #bbs () returns worth the right return

——-——————

OK, the problem with the return value is resolved.

Since the adorner is a function, can the adorner have parameters?

The answer is yes. We can also add parameters to the adorner. For example, the above three page function as an example, we can according to different page verification method to give the program different validation, and this authentication method can be passed in the adorner parameters, so we have to be nested in the adorner layer function:

 1 username,passwd= "Jack", "Abc123" #模拟一个已登录用户 2 def Decorator (Auth_type): 3 def out_warpper (func): 4 def Warppe             R (*args,**kwargs): 5 username=input ("Username:"). Strip () 6 password=input ("Password:"). Strip () 7 If auth_type== "local": 8 if Username==username and Passwd==password:9 Prin T ("Authenticate success!") Ten return func (*args,**kwargs) Else:12 exit ("Username or Passwor D is invalid! ") elif auth_type==" unlocal ": Print (" Here's unlocal authenticate WAYS ") return Warpper16 return Out_warpper17 def index (): Print ("Welcome to the index page") @decorator (auth_type= "local") ) def home (): Print ("Welcome to the Home page") @decorator (auth_type= "unlocal") def BBS (): Print ("welcom E to the BBS page ") + return" I am the Return Contents "index () () Home () BBS ()

Output:

————————

Welcome to the index page
Username:jack
Password:abc123
Authenticate success!
Welcome to the Home page
Username:jack
Password:abc123
Here is unlocal authenticate WAYS

————————

As can be seen, the program is added to the 2nd and 16th lines and the middle of the relevant content according to the Auth_type parameters, to solve the above problem. For the above three-layer nesting of related logic, you can add breakpoints in the Pycharm, and gradually debug, you can find the truth.

Summarize

To learn the iterator, you have to understand three articles:

1. function is a variable (that is, the concept of a function object)

2. Function nesting

3. Functional programming

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.