Python notes • 11th-function (ii) decorators

Source: Internet
Author: User
Tags wrapper

Why use an adorner?

Sometimes write a piece of code, over a period of time need to upgrade it, add some new features, but if you want to directly modify the original code will affect other people's call, so you need a not to modify the source code and do not modify the original function of the invocation of things and can add new functionality to the original function of the thing, the adorner is doing this

Two what is an adorner
the utensil of another person can be any callable object, and the adorner can be any callable object. The principle of the adorner is emphasized:12  do not modify the calling style of the decorated object the target of the adorner: Add a new feature to the decorated object, subject to 1 and 2
Open closure principle: Closed to modification, open to expansion
use of three adorners

The following is an adorner for a function that adds the ability to calculate its run time:

1 Import Time2 defTimmer (func):3     defWrapper (*args,**Kwargs):4Start_time=time.time ()5Res=func (*args,**Kwargs)6Stop_time=time.time ()7         Print('run time is%s'% (stop_time-start_time))8         returnRes9     returnwrapperTen  One @timmer A deffoo (): -Time.sleep (3) -     Print('From foo') the foo ()

Four, the decorator syntax and fixed format
1 def Adorner function name (func): 2     def Wrapper (*args,**Kwargs):    3         ret = func (*args,**Kwargs)4          return  ret5     return  wrapper6 7 @ Adorner function name 8 def func (): 9    Pass
Five, homework practice
1 ###################################### #作业练习 #######################################################2 #Job:3 #1. Compose the adorner, add the function of authentication to multiple functions (the user's account password originates from the file), require the login to be successful once, subsequent functions no longer need to enter the user name and password4 #user_exist = [False]5 #def Auth (func):6 #def wrapper (*args,**kwargs):7 ##注册功能8 #With open (' Db.txt ', ' R ', encoding= ' utf-8 ') as F:9 #user_dic = eval (F.read ())Ten #flag = False One #While not User_exist[0]: A #username = input (' Please enter your user name: '). Strip () - #password = input (' Please enter your password: '). Strip () - #if username in user_dic and password = = User_dic[username]: the #print (' Congratulations, login successful! ') - #user_exist[0] = True - # Break - #Else: + #print (' Account or password error, please re-enter! ') - #ret = func (*args,**kwargs) + #return ret A #return wrapper at # - #@auth - #def func1 (): - #print (' function 1 ') - #@auth - #def func2 (x): in #print (' function 2 ', x) - #func1 () to #Func2 (111111) + #2. Writing adorners, adding a record call function to multiple functions, requires each call function to write the called function name to the file - #def log (func): the #def wrapper (*args,**kwargs): * #With open (' db2.txt ', ' a ', encoding= ' utf-8 ') as F: $ #f.write ('%s ' function is being called. \ n '%func.__name__)Panax Notoginseng #ret = func (*args,**kwargs) - #return ret the #return wrapper + #@log A #def func1 (): the #print (' func1 function was called .... ') + #@log - #def func2 (): $ #print (' Func2 function was called .... ') $ # - #func1 () - #Func2 () the #Advanced operation (optional): - #1. Write a function to download the content of the webpage, the function is: the user passes in a URL, the function returns the result of the download pageWuyi  fromUrllib.requestImportUrlopen the  - #def get_html (URL): Wu #print (Urlopen (URL). Read ()) - # About #get_html (' http://www.baidu.com ') $ #2. To write the adorner for topic 1, the ability to cache Web content: - #specific: The implementation of the download page is stored in the file, if the file has a value (the file size is not 0), the priority is to read the page content from the file, otherwise, to download, and then save to the file - #From urllib.request import Urlopen - #  A #def Get_bak (func): + #def wrapper (*args,**kwargs): the #With open (' Html.bak ', ' r+ ', encoding= ' utf-8 ') as F: - #if not F.read (): $ #ret = func (*args, **kwargs) the #print (ret) the #f.write (Ret.decode (' Utf-8 ')) the #Else: the #print (' The following is from the cache ^ ^^ ^^ ') - #f.seek (0) in #print (F.read ()) the #ret = func (*args, **kwargs) the #return ret About #return wrapper the #  the #@get_bak the #def get_html (URL): + #return Urlopen (URL). Read () - #get_html (' http://www.python.org ')

Python notes • 11th-function (ii) decorators

Related Article

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.