python-装饰(高阶函数)

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
原文地址:https://www.cnblogs.com/kezi/p/11986696.html