学习pyhton装饰器笔记。

python的装饰器,其本质就是通过一个函数来给另外一个函数增加新的功能。

装饰器的特性:

1.不修改被修饰函数的源代码。
2.不修改被修饰函数的调用方式。

在你的项目中,调用的大量的函数,那么可以使用这种方式来给正在使用的项目增加新的功能,但是却不影响使用,所以装饰器还是非常实用的。

装饰器是有高阶函数和嵌套函数组成的。

高阶函数:
高阶函数的特性:

a.将一个函数的函数名当做实参传递给另一个函数.
b.在函数的返回值中包含函数名
import time

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

运行的结果:
在等待三秒后,会打印出 in the bar
随后会打印出 the func run time is 3.000171422958374

in the bar
the func run time is 3.000171422958374

这里的test(bar),返回的就是def bar 的函数名,它的意思就是将bar函数的内存地址传递给了参数func,在后面的func()时,其实等同于 bar(),这样就实现了调用bar函数。

嵌套函数:
在一个函数的内部,再次定义一个函数。

#函数的嵌套一定是在函数的内部进行定义
def test1():
	print(in the test1)
	def test2():
		print(in the test2)
	test2()
test1()

#注意区分函数的调用和函数的嵌套
#函数的调用
def foo():
	test1()
foo()

在具备了以上两个条件,高阶函数和嵌套函数后,就可以成为一个装饰器了。
第一步

#我们先定义一个基本函数
def test1():
    time.sleep(3)
    print('in the test1')

第二步

#使用装饰器给test1新增功能
#注意嵌套函数和高阶函数
def deco(func):
    def test2():
        start_time = time.time()
        func()
        end_time = time.time()
        print('the func run time is %s' %(end_time - end_time))
    return test2
    #这里返回test2是使用高阶函数,目的是将test2的内存地址返回

第三步

#最后调用的test1函数
test1()

这时,基本就已经完成了,但是运行之后还是没有增加新功能。
那是因为我们没有调用装饰器。
调用装饰器我们需要使用 语法糖。
格式为 @deco
我们需要将它放在我们需要装饰的函数之上,也就是

@deco 
def test1():
    time.sleep(3)
    print('in the test1')

语法糖的功能等同于test1 = deco(test1)
这样我们就可以实现装饰器的功能了,在不修改被装饰函数的源代码和调用方式的同时,还可以增加新功能。
下面是完整的代码。
有错请指出,虚心学习。轻喷勿骂。

import time

#使用装饰器给test1新增功能
#注意嵌套函数和高阶函数
def deco(func):
    def test2():
        start_time = time.time()
        func()
        end_time = time.time()
        print('the func run time is %s' %(end_time - start_time))
    return test2
    #这里返回test2是使用高阶函数,目的是将test2的内存地址返回

#我们先定义一个基本函数
@deco
def test1():
    time.sleep(3)
    print('in the test1')


#下面调用test1函数
test1()

结果

in the test1
the func run time is 3.000171422958374
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值