The path to python: wupeiqi

Source: Internet
Author: User

The path to python: wupeiqi

Decorator:

Itself is a function (decorated with other functions), that is, adding the attachment function for other functions

Principles:

(1) the source code of the decorated function cannot be modified.

(2) The call method of the decorated function cannot be modified.

Implement the knowledge reserve of the decorator:

(1) A function is a variable"

(2) Higher-Order Functions

A: pass a function name as a real parameter to another function.

B: The returned value contains the function name.

(3) nested Functions

Decorator = high-order functions + nested Functions

 

I have two functions. I want to add the log printing function for both functions. I can modify the content of each function.

1 def test1 (): 2 pass 3 def test2 (): 4 pass 5 modify each function to add a piece of code. After modification, 6 def test1 (): 7 print ("log ") 8 pass 9 def test2 (): 10 print ("log ")
View Code

This method is obviously stupid. If the new function requires 1000 rows, I need to write another 1000 rows for each function... We have learned to define functions to save code reuse.

1 def test1 (): 2 pass 3 def test2 (): 4 pass 5 defines a log function and adds this function to two of my functions to use 6 def log (): 7 print ("log") 8 def test1 (): 9 log () 10 pass11 def test2 (): 12 log () 13 pass
View Code

In this way, although I can save adding 1000 rows in each function, my source code is modified. What if I need to modify 1000 functions? What if I want to remove this function and then write a new function if it doesn't work well after I add it? Modifying source code is certainly not a good method. We have learned advanced functions before. Can I pass the code I want to execute into my log functions as parameters, and then execute the log function? Try it!

1 def log (func): 2 print ("log") 3 func () 4 def test1 (): 5 pass 6 def test2 (): 7 pass 8 9 run 10 log (test1) 11 log (test2)
View Code

But I have other code that will use these two functions. After I modify these functions, I also need to modify them when other code calls them, what if I have a lot of code to call these two functions? Can I modify the call method without modifying it?

1 def log (func): 2 print ("log") 3 return func 4 def test1 (): 5 pass 6 def test2 (): 7 pass 8 execution 9 test1 = log (test1) 10 test1 () 11 test2 = log (test2) 12 test2 ()
View Code

This is much better. I solved the above problem, but have you found that I need to assign values without stopping them and then call them like before? The assignment is required for the first 1000 functions... Tired. This is the time when the decorator debuted.

1 def log (func): 2 wrapper (): 3 print ("log") 4 func () 5 return wrapper 6 7 @ log 8 test1 (): 9 pass10 @ log11 test2 (): 12 pass13 execute 14 test1 () 15 test2 ()
View Code

This is a simple decorator. It does not modify the source code or call method of the original function, but adds @ log syntax sugar to the original function, now I have another test3 function that needs to add the log function, but test3 and 1 and 2 are different. test3 has parameters. How can this problem be solved? How can I make the decorator match every function?

 1 def log(func): 2     def wrapper(*args,**kwargs): 3         print ("log") 4         func(*args,**kwargs) 5     return wrapper 6 @log 7 def test1(): 8     pass 9 @log10 def test2():11     pass12 @log13 def test3(name):14     print (name)
View Code

Can I add parameters to the decorator? The answer is OK.

 1 import time 2  3 user,passwd = "admin","admin123" 4  5 def auth(auth_type): 6     print ("auth func:",auth_type) 7     def outer_wrapper(func): 8         def wrapper(*args, **kwargs): 9             print("wrapper func:", *args,**kwargs)10             if auth_type == "local":11                 username = input("Username:").strip()12                 password = input("Password:").strip()13                 if user == username and passwd == password:14                     print("\033[32;1mUser has passed authentication\033[0m")15                     res = func(*args, **kwargs)16                     print("---after authentication")17                     return res18                 else:19                     exit("\033[31;1mInvalid username or password\033[0m")20             elif auth_type == "ldap":21                 print ("ldap bu hui...")22         return wrapper23     return outer_wrapper24 25 def index():26     print ("welcome to index page")27 @auth(auth_type="local")    #home=wrapper()28 def home():29     print ("welcome to home page")30     return "from home"31 @auth(auth_type="ldap")32 def bbs():33     print ("welcome to bbs page")34 index()35 print (home())36 bbs()
View Code

Now the decorator has almost understood it. There is a small problem. If my original function has a return value, why didn't I get the return value after I added the decorator?

Where do you need to return your returned results?

1 def log (func): 2 def wrapper (* args, ** kwargs): 3 print ("log") 4 res = func (* args, ** kwargs) 5 return res 6 return wrapper 7 @ log 8 def test1 (): 9 return "test1" 10 then execute try 11 test1 ()
View Code

 

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.