装饰函数

1、函数即变量2、高阶函数

  a、把一个函数名当做实参创给另一个函数;

import time
def bar():
    print('in the bar')

def test(func):
    start_tmie=time.time()
    func()
    stop_time=time.time()
    print('the func run time is %s'%(stop_time-start_tmie))
test(bar)

  b、返回值包含函数名,不用修改函数的调用方式

import time
def bar():
    time.sleep(3)
    print("in the bar")
def test2(func):
    print(func)
    return func
bar=test2(bar)
bar()
函数嵌套
def test01():
    print('in the test01')
    def test02():
        print('in the test02')
    test02()
test01()
######打印结果#####
in the test01
in the test02


全局作用域和局部作用域

3、装饰函数

高阶函数+嵌套函数=装饰函数
# Aduthor:CCIP-Ma
import time
def timer(func):
    def deco():
        start_time=time.time()
        func()
        stop_time=time.time()
        print('the time %s'%(stop_time-start_time))
    return deco   #返回门牌号,内存地址
@timer   #test1=timer(test1)  意思一样
def test1():
    time.sleep(3)
    print('in the test1')
test1()




猜你喜欢

转载自www.cnblogs.com/ccip-ma/p/906d7474f867e1888f5582216202d32d.html