首页 > 编程语言 > 详细

python-装饰(高阶函数)

时间:2019-12-05 09:46:45      阅读:84      评论:0      收藏:0      [点我收藏+]

python-装饰(高阶函数)

高阶函数

  1、把一个函数名当做实参传给另外一个函数(在不修改被装饰函数源代码)

  2、返回值 中包含函数名

高阶函数实现1的功能

def bar():
    print("in the bar")
def  test1(func):
    print("in the test1")
    print(func)
    func()   #func=bar    func()=bar()
test1(bar)


打印结果
---------------------------------

in the test1
<function bar at 0x000001DA445500D0>
in the bar

#实现bar的运行时间的高阶函数
import
time def bar(): time.sleep(3) print("in the bar") def test1(func): star_time=time.time() func() #bar() stop_time=time.time() print("the func run time is %s"%(stop_time-star_time)) test1(bar)
打印结果
----------------------------------- in the bar the func run time is 3.0002150535583496

第二个功能实现

import time

def bar():
    time.sleep(3)
    print("int the bar")
def test2(func):
    print(func)
    return func
print(test2(bar))

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

bar=test2(bar)  #覆盖原来的bar
bar()       #不修改原来的调用方式

打印结果
——————————————————————————
<function bar at 0x00000224596500D0>
<function bar at 0x00000224596500D0>
<function bar at 0x00000224596500D0>
<function bar at 0x00000224596500D0>
int the bar
<function bar at 0x00000224596500D0>
<function bar at 0x00000224596500D0>
int the bar

 

python-装饰(高阶函数)

原文:https://www.cnblogs.com/kezi/p/11986696.html

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