Python装饰器2

高阶函数:

a:把一个函数名当做实参传给另外一个函数

(在不修改被装饰函数源代码的情况下为其添加功能)

import time
def bar():
    time.sleep(3)
    print('in the bar')
def test(func):
    start_time=time.time()
    func()      #run  bar
    stop_time=time.time()
    print('the func run time is %s'%(stop_time-start_time))
test(bar)

b:返回值中包含函数名(不修改函数的调用方式)

import time
def bar():
    time.sleep(3)
    print('in the bar')
def test2(func):#传入函数的内存地址
    print(func)
    return func
print(test2(bar))
t=test2(bar)
t()
这个的结果很有趣:

<function bar at 0x000002CBDFF0A8C8>
<function bar at 0x000002CBDFF0A8C8>
<function bar at 0x000002CBDFF0A8C8>
in the bar

出现了3次打印内存地址

print(test2(bar))打印了两次地址

结果显示了bar的内存地址,bar是门牌号。

嵌套函数:

def foo():
    print('in the foo')
    def bar():  #一定要定义嵌套,不然只能看作函数调用
        print('in the bar')
    bar()
foo()
装饰器=高阶函数+嵌套函数

import time
def timer(func):    #timer(test1)   func=test1
    def deco(*args,**kwargs):   #增加新功能的函数,可变参数是增强装饰器的适应能力
        start_time=time.time()
        func(*args,**kwargs)  #run old version
        stop_time=time.time()
        print('the func run time is %s'%(stop_time-start_time))
    return deco     #返回内存地址
@timer      #等价于test1=timer(test1)
def test1():
    print('in the test1')
    time.sleep(1)
@timer      #等价于test2=timer(test2)
def test2():
    print('in the test2')
    time.sleep(1)
@timer
def test3(*args):
    print('in the test3')
    time.sleep(1)
    print(args)
@timer
def test4(**kwargs):
    print('in the test4')
    time.sleep(1)
    print(kwargs)
test1()
test2()
test3('coke','19')
test4(sex='male')

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值