首页 > 其他 > 详细

装饰函数

时间:2020-01-06 11:17:35      阅读:90      评论:0      收藏:0      [点我收藏+]

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()




装饰函数

原文:https://www.cnblogs.com/ccip-ma/p/906d7474f867e1888f5582216202d32d.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!