Road Python learning 6 - decorator

Definitions : essentially a function (other decorative function) is to add additional functionality to other functions.
Principle : 1. modification function can not be decorated source
   2 can not be modified to be decorated is called by the function

Achieve a decorator's knowledge base:
  1. function that is "variable"
  2. The higher-order functions (one of the following conditions is higher-order functions)

    • a: the function name as a parameter passed to another function (modify its function without modifying the source code where decorative function, but the call mode changed)
    • b: Returns the value contained in the function name (without modifying the function is called, and the function-modified)

  3. nested functions

to sum up:

+ Higher order functions nested function => decorator


1. That variable function

def bar():  #这里定义个函数
    print('this is bar...')

func = bar  #将函数当变量一样赋值给func

func()  #这是func加上()就可以当函数用了

  This is the function that is variable.

2. Higher-order functions

a: the function name as a parameter passed to another function (function without modifying other modifications are where decorative function of the source code, but the call mode changed)

def bar():
    print('this is bar...')
bar()
print('----------------------------------')
def test(func): #在这里增加了功能
    print(func)
test(bar)  #但是这里修改了调用方式

b: Returns the value contained in the function name (without modifying the function is called, and the function-modified)

def bar():
    print('this is bar...')
bar()
print('----------------------------------')
def test(func):   #在这里增加了功能
    print(func)
    return func     #这里返回了函数地址
bar = test(bar)   #将函数地址赋给一个变量,该变量和传入函数同名
bar()       #这个变量加上括号,就可以当函数用了,同时又没有修改函数的调用方式

3. nested functions

x = 1
def test1():
    def test2():
        def test3():
            x = 3
            print(x)
        test3()
    test2()
test1()

  In this manner a function which defines a function is called a nested function.

Knowledge is now three points already explained, following the first realization of a primitive version of the decorator.

The original version of the decorator

import time

def test1():  #这里是被装饰的函数
    time.sleep(1)
    print("this is test1....")

def timer(func):  #这里是装饰器函数
    def deco():
        strat = time.time()
        func()
        stop = time.time()
        print("run time %s" %(stop-strat))
    return deco

test1 = timer(test1)

test1()

  The decorator function is to run the test test1 function of time, deco functions have this feature, so here I actually want to run a deco function, timer () function's return value is the address deco function; the function you want to run simultaneously deco we need to meet the other conditions that need to call the timer function, timer function to write those things which take effect or to be activated only when the timer function is running, deco function will define success. This, test = timer (test1) of this code means that, first call the timer function so that the function defined deco entry into force at the same time address to be decorated function function test1 passed, let deco inside the function func function to take effect, which a timer function and the function's return address will deco and test1 address assigned to this variable. Then the following parentheses behind test1, into forms test1 (), you can run. Such a primitive version of the decorator on finished.

Next, write a real decorator examples

import time

def timer(func):
    def deco():
        start_time = time.time()
        func()
        stop_time = time.time()
        print('the func run time is %s' %(stop_time-start_time))
    return deco

@timer  #这里等于 test = timer(test),要装饰哪个函数,就在哪个函数前面加上这个
def test():
    time.sleep(2)
    print('this is test...')

test()

  Above these are some of the more basic, if decorated with parameter function and the number of parameters still not certain how to do it? The following write a high-level case - with arguments decorator

Advanced Case - there are parameters decorator

import time

def timer(func):
    def deco(*args,**kwargs):  #在这里接收参数
        start_time = time.time()
        func(*args,**kwargs)
        stop_time = time.time()
        print('the func run time is %s' %(stop_time-start_time))
    return deco

@timer
def test(name):
    time.sleep(2)
    print('this is test...',name)

test('vector')

  If the original test function which returns a value, after being decorated we print it print (test ()), the result will be none. Because at this time test = deco, the deco no return value, it does not print. So there will be a problem, if the test function returns a value, a function test function (return value) will be lost.

Solution See the following cases.

High Advanced Case - decorator has a return value

import time
def timer(func):
    def deco(*args,**kwargs):
        start_time = time.time()
        res = func(*args,**kwargs)
        stop_time = time.time()
        print('the func run time is %s' %(stop_time-start_time))
        return res  #这里将func的返回值返回
    return deco

@timer
def test(name):
    time.sleep(2)
    print('this is test...',name)
    return 'asdfasdfgdfgd'

print(test('vector'))

  So that you can print out the return value.

Sometimes we also need to pass arguments to the decorator, for internal use. Solution see below.

Advanced Case high - pass parameters to the decorator

import time
def timer(temp):
    print('this is ',temp)  #这里是加进来的参数
    def out(func):
        def deco(*args,**kwargs):
            start_time = time.time()
            res = func(*args,**kwargs)
            stop_time = time.time()
            print('the func run time is %s' %(stop_time-start_time))
            return res
        return deco
    return out

@timer('temp')
def test(name):
    time.sleep(2)
    print('this is test...',name)
    return 'asdfasdfgdfgd'

print(test('vector'))

  Is actually a whole and on the outside add a layer of built-in functions.

Guess you like

Origin www.cnblogs.com/imzry/p/11885664.html