Python装饰器基础知识

装饰器:本质是函数(装饰其他函数)就是为其他函数添加附加功能

原则:

1、不能修改被装饰的函数的源代码

2、不能修改被装饰的函数的调用方式

装饰器对其被装饰的函数是完全透明的

基础知识

1、函数即“变量”   定义一个函数相当于就是把函数体赋值给函数名

def test():

    pass

test -->>'函数体'

2、高阶函数 

1、把一个函数名当作实参传给另外一个函数(在不修改被装饰函数源代码的情况下为其添加功能) 2、返回值中包含函数名(不修改函数的调用方式)

import  time
def  bar():
    time.sleep(3)
    print('in the bar')

def test1(func):
    start_time = time.time()
    func()  #run bar
    stop_time = time.time()
    print('the fun run time is %s' %(stop_time-start_time))


test1(bar)
bar()

import  time
def bar():
    time.sleep(3)
    print('in the bar')


def test2(func):
    print(func)
    return func

test2(bar)

bar = test2(bar)
bar()

3、嵌套函数

foo():
    ()
    bar():
        ()
    bar()

foo() 

高阶函数+嵌套函数 =》装饰器

1、不带参数的装饰器

import time

def timer(func):  #timer(test1)  func=test1

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

@timer  #test1 = timer(test1)  等同于这个,得到的是deco函数的返回值
def test1():
    time.sleep(3)
    print('in the test1')


test1()  #--->deco

代码执行过程

1、导入模块

2、def timer(func)

3、@timer   自动执行将test1传递给timer函数执行,之后返回deco函数的返回值

4、当执行到test1()函数时候,跳转到deco函数去执行

2、带参数的装饰器

import time

def timer(func):  #timer(test1)  func=test1

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

@timer  #test1 = timer(test1)  等同于这个
def test1(name):
    time.sleep(3)
    print('in the test1',name)


test1('martin')  #--->deco(‘martin’)

import time

def timer(func):  #timer(test1)  func=test1

    def deco(*args,**kwargs):
        start_time = time.time()
        func(*args,**kwargs)  #run test1
        stop_time = time.time()
        print('the fun run time is %s' %(stop_time-start_time))
    return deco

@timer  #test1 = timer(test1)  等同于这个
def test1():
    time.sleep(3)
    print('in the test1')

@timer
def test2(name,age):
    time.sleep(3)
    print('in the test2',name,age)

#test1 = timer(test1)
print(test1)
test1()  #--->deco
test2('martin',18) 

猜你喜欢

转载自www.linuxidc.com/Linux/2018-08/153714.htm