Python笔记:Python装饰器


装饰器是通过装饰器函数修改原函数的一些功能而不需要修改原函数,在很多场景可以用到它,比如① 执行某个测试用例之前,判断是否需要登录或者执行某些特定操作;② 统计某个函数的执行时间;③ 判断输入合法性等。合理使用装饰器可以极大地提高程序的可读性以及运行效率。本文将介绍Python装饰器的使用方法。

python简单装饰器

python装饰器可以定义如下:

def my_decorator(func):
    def wrapper(*args, **kwargs):
        print('this is wrapper')
        func(*args, **kwargs)
        print('bye')
    return wrapper

def test_decorator(message):
    print(message)

decorator = my_decorator(test_decorator)
decorator('hello world')

输出:

this is wrapper
hello world
bye

python解释器将test_decorator函数作为参数传递给my_decorator函数,并指向了内部函数 wrapper(),内部函数 wrapper() 又会调用原函数 test_decorator(),所以decorator()的执行会先打印’this is wrapper’,然后打印’hello world’, test_decorator()执行完成后,打印 ‘bye’ ,*args和**kwargs,表示接受任意数量和类型的参数。

装饰器 my_decorator() 把真正需要执行的函数 test_decorator() 包裹在其中,并且改变了它的行为,但是原函数 test_decorator() 不变。

一般使用如下形式使用装饰器:

@my_decorator
def test_decorator(message):
    print(message)

test_decorator('hello world')

@my_decorator就相当于 decorator = my_decorator(test_decorator) 语句。

functools()

内置装饰器@functools.wrap可用于保留原函数的元信息(将原函数的元信息,拷贝到对应的装饰器函数里)。先来看看没有使用functools的情况:

def my_decorator(func):
    def wrapper(*args, **kwargs):
        print('this is wrapper')
        func(*args, **kwargs)
    return wrapper

@my_decorator
def test_decorator(message):
    print(message)

test_decorator('hello world')
print(test_decorator.__name__)
print("######")
help(test_decorator)

输出:

this is wrapper
hello world
wrapper
######
Help on function wrapper in module __main__:

wrapper(*args, **kwargs
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值