python-装饰(高阶函数)

♀尐吖头ヾ 提交于 2019-12-27 17:00:28

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

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!