装饰器

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

原则:1,不能修改被装饰函数的原代码。

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

 

import time

def timer(func):
    def warpper(*args,**kwargs):
        start_time=time.time()
        func()
        stop_time=time.time()
        print("The func run time is %s " %(stop_time-start_time))
    return warpper

@timer
def test1():
    time.sleep(3)
    print("in the test1")

@timer
def test2():
    time.sleep(5)
    print("in the test2")

test1()
test2()

 

实现装饰器的功能:1。函数就是变量。

2、高阶函数。

a。把一个函数当和一个形参传递给另一个函数当实能。b、当返回值中包含函数名。

def bar():
    print("in the bar")

def test1(func):
    print(func)

test1(bar)
test1(bar())
'''def bar():
    print("in the bar")

def test1(func):
    print(func)

test1(bar)
test1(bar())'''

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

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

#print(test2(bar))
t=test2(bar)
#print(t)
t() #run bar

 

3、嵌套函数。

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

posted @ 2020-02-12 02:34  奔腾的小河  阅读(88)  评论(0编辑  收藏  举报