Python Basics four: adorners

Source: Internet
Author: User
Tags wrapper

Adorner essence: function, function is to add additional functions for other functions

Adorner principle:

    1. Do not modify the source code of the modified function
    2. Do not modify the calling method of a decorated function

Knowledge Reserve for Decorators:

Adorner = higher order function + function nesting + closure

First Knowledge decorator

Let's look at a requirement: The following function is used to calculate the 1 to 20 and

def calc(l):    res = 0    for i in l:        time.sleep(0.01)        res += i    return resresult = calc(range(1,21))print(result)

But now the demand has changed, not only to calculate 1 to 20 of the and, but also need to calculate the function of the time of operation, when the adorner should be required to live

import timedef timer(func):    def wrapper(*args,**kwargs):        start_time = time.time()        res = func(*args,**kwargs)        stop_time = time.time()        print(‘函数运行的时间为:%s‘ % (stop_time - start_time))        return res    return wrapper@timerdef calc(l):    res = 0    for i in l:        time.sleep(0.01)        res += i    return resresult = calc(range(1,21))print(result)

The results of the operation are as follows:

函数运行的时间为:0.2048475742340088210

The timer function above is the adorner for the Calc function.

Higher order functions

Higher-order function definitions:
1. The parameter received by the function is a functional name

2. The return value of a function is a functional name

3. Any one of the above conditions can be called the higher order function

Example of a higher order function
def foo():    print(‘我的函数名作为参数传给高阶函数‘)def gao_jie1(func):    print(‘我就是高阶函数1,我接收的参数名是%s‘ %func)    func()def gao_jie2(func):    print(‘我就是高阶函数2,我的返回值是%s‘ %func)    return funcgao_jie1(foo)gao_jie2(foo)
Passing functions as parameters to higher-order functions
#高阶函数应用1:把函数当做参数传给高阶函数import timedef foo():    print(‘from the foo‘)def timmer(func):    start_time=time.time()    func()    stop_time=time.time()    print(‘函数%s 运行时间是%s‘ %(func,stop_time-start_time))timmer(foo)#总结:我们确实为函数foo增加了foo运行时间的功能,但是foo原来的执行方式是foo(),现在我们需要调用高阶函数timmer(foo),改变了函数的调用方式
The function return value is the name of the functor
#高阶函数应用2:把函数名当做参数传给高阶函数,高阶函数直接返回函数名import timedef foo():    print(‘from the foo‘)def timmer(func):    start_time=time.time()    return func    stop_time=time.time()    print(‘函数%s 运行时间是%s‘ %(func,stop_time-start_time))foo=timmer(foo)foo()#总结:我们确实没有改变foo的调用方式,但是我们也没有为foo增加任何新功能

Summary of higher order functions
1. The parameter received by the function is a functional name
Function: Add a new function to the function without modifying the source code of the function.
Insufficient: Changes the way the function is called
2. The return value of a function is a functional name
Function: Does not modify the function's Calling method
Insufficient: Cannot add new features

function nesting
def father(name):    print(‘from father %s‘ %name)    def son():        print(‘from son‘)        def grandson():            print(‘from grandson‘)        grandson()    son()father(‘Poe‘)
Closed Package
‘‘‘闭包:在一个作用哉里放放定义变量,相当于打了一个包‘‘‘def father(name):    def son():        print(‘My father is %s‘ %name)        def grandson():            print(‘my grandpa is %s‘ %name)        grandson()    son()father(‘Poe‘)
No parameter Adorner

No parameter Adorner = Advanced function + function nesting

Basic framework

‘‘‘这就是一个实现 装饰器最基本的架子‘‘‘def timer(func):    def wrapper():        func()    return wrapper()

Back to the need to calculate the function run time, add the following code without using the adorner

import timedef timer(func):    def wrapper():        startTime = time.time()        func()        stopTime = time.time()        print(‘函数运行时间为:%s‘ % (stopTime - startTime))    return wrapperdef test():    time.sleep(3)    print(‘test函数运行完毕‘)res = timer(test)res()

Using adorners

import timedef timer(func):    def wrapper():        startTime = time.time()        func()        stopTime = time.time()        print(‘函数运行时间为:%s‘ % (stopTime - startTime))    return wrapper@timer  #相当于test = timer(test)def test():    time.sleep(3)    print(‘test函数运行完毕‘)test()

return value problem
If there is a return value in the test function, how do I return it? When the test function is called, the essence is to call the wrapper function, if you want to return the value in the test function, you must return the value in the wrapper function

import timedef timer(func):    def wrapper():        startTime = time.time()        res = func()        stopTime = time.time()        print(‘该函数运行时间为:%s‘ % (stopTime - startTime))        return res    return wrapper@timerdef test():    time.sleep(1)    print(‘该函数运行完毕‘)    return ‘这是test的返回值‘res = test()        #实质调用的是wrapper函数print(res)
Adorner with parameters
import timedef timer(func):    def wrapper(*args,**kwargs):        startTime = time.time()        res = func(*args,**kwargs)        stopTime = time.time()        print(‘该函数运行时间为:%s‘ % (stopTime - startTime))        return res    return wrapper@timer  #test = timer(test)def test(name,age):    time.sleep(1)    print(‘该函数运行完毕,name is %s,age is %s‘ %(name,age))    return ‘这是test的返回值‘res = test(‘andy‘,18)        #实质调用的是wrapper函数print(res)
Supplemental Knowledge: Extracting sequences
>>> a,b,c=(2,3,4)>>> a2>>> b3>>> c4

A, B, c variables must correspond to element one by one in the tuple to fetch the value
So look at one more example:

>>> l=[1,2,3,4,5,6,7,8]

How to get the first element and the last element in the list above using the sequence method

>>> l=[1,2,3,4,5,6,7,8]>>> l[1, 2, 3, 4, 5, 6, 7, 8]>>> a,*_,c=l>>> a1>>> c8>>> a,*b,c=l>>> a1>>> b[2, 3, 4, 5, 6, 7]>>> c8

Note: The number represents all elements except the A,C variable , which must have a variable followed by an underscore to indicate that the variable does not want to be removed

This method can be used to exchange the values of two variables:

>>> a=1>>> b=2>>> a,b=(b,a)>>> a2>>> b1
Adorner example
User_list = [{' name ': ' Andy ', ' passwd ': ' 123 '}, {' name ': ' Bruce ', ' passwd ': ' 123 '}, {' name ': ' Poe ', ' passwd ': ' 123 '}, {' name ': ' Jacky ', ' passwd ': ' 123 '},]current_dic = {' username ': None, ' login ': False}def auth_func (func): Def wrapper (*            Args,**kwargs): If current_dic[' username ' and current_dic[' login ']: res = func (*args,**kwargs) return res username = input (' username: '). Strip () Password = input (' Password: '). Strip () for User_di C in user_list:if username = = user_dic[' name '] and password = = user_dic[' passwd ']: current_dic[                ' Username ' = Username current_dic[' login '] = True res = func (*args,**kwargs) return res else:print (' Username or password error ') return Wrapper@auth_funcdef index (): print (' Welcome to JD Homepage ') @auth_f Uncdef Home (name): Print (' Welcome%s to home '% name) @auth_funcdef Shopping (name): Print ('%s ' cart has%s,%s,%s '% (name, ' Milk tea ', ' sister ', ' toothpaste ') print (' Before:', Current_dic) index () Home (' Andy ') shopping (' Andy ') print (' After: ', current_dic) 

Code Execution Results:

before :  {‘username‘: None, ‘login‘: False}username:andypassword:123欢迎来到JD主页welcome andy to homeandy的购物车里有奶茶,妹妹,牙膏after:  {‘username‘: ‘andy‘, ‘login‘: True}

Python Basics four: adorners

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.