python装饰器高级用法(一文搞懂python中最强大的装饰器)

装饰器是python中的进阶用法,应用范围非常广泛,作为数据分析师,我们要功课之一难题,很多人都觉得装饰器难以理解,以至于不敢去尝试,难以突破瓶颈。今天,我将带领大家由浅入深的理解装饰器,并且掌握装饰器在工作中的应用。

python装饰器高级用法(一文搞懂python中最强大的装饰器)(1)

1、简单装饰器

def check(func): def wrapper(): print('this is check') func() return wrapper ​ ​ @check def hello(): print('hello wrapper') ​ hello()

输出:

this is check hello wrapper

直接看代码,执行hello函数之前,装饰器首先打印出了 this is check。

2、带有参数的装饰器

def check(func): def wrapper(word): print('this is check') func(word) return wrapper ​ ​ @check def hello(word): print('hello {0}'.format(word)) ​ hello('every one')

输出:

this is check hello every one

我们更进一步,如果原函数当中带有参数,我们对应的也应该在装饰器中加入参数。

这时候又有新的问题了,如果有两个原函数同时使用了一个装饰器,但两个原函数的参数不同,我们上面这种写法就无法满足情况了,所以我们引入了一种新的写法:

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

关于*args, **kwargs的使用,在这里就不再赘述了,我之前的文章中有详细的介绍。

python装饰器高级用法(一文搞懂python中最强大的装饰器)(2)

3、装饰器的嵌套

我们先来看一个现象:

def check1(func): def wrapper(*args, **kwargs): print('this is check 1') func(*args, **kwargs) return wrapper ​ def check2(func): def wrapper(*args, **kwargs): print('this is check 2') func(*args, **kwargs) return wrapper ​ @check2 @check1 def hello(word): print('hello {0}'.format(word)) ​ ​ hello('every one')

输出:

this is check 2 this is check 1 hello every one

在这里我们可以看到,一个函数可以被多个装饰器装饰,并且是从上往下运行。

python装饰器高级用法(一文搞懂python中最强大的装饰器)(3)

4、装饰器的实际用途

4.1、身份认证

举个例子,比如说我们要根据部门,批量给公司的员工发邮件,为了防止发给给其他部门的人,就需要先验证邮箱是否处于目标部门:

def check(func): def wrapper(*args, **kwargs): user = args[0] if user in department: return func(*args, **kwargs) else: raise Exception('user is not in department') return wrapper ​ ​ @check def send_email(user_email, ...): ...

上面的简单示例,是先定义一个check装饰器,如果send_email中的参数user_email不在department中,就抛出一个错误,提醒我们去核查用户邮箱。

4.2 日志记录

日志记录中也常常需要用到装饰器,比如说随着业务量的增大,我们的方法越来越多,但也导致了整个系统越来越慢,这时候需要检查一下到底哪个方法执行的最慢,所以我们需要给函数加上装饰器,记录程序执行时间的长短;

def check(func): def wrapper(*args, **kwargs): start = time.time() result = func(*args, **kwargs) end = time.time() print(end-start) return result return wrapper ​ ​ @check def program(): ...

4.3 输入合理性检查

作为数据分析师,我们那面要跟sql打交道,尤其是在写脚本的时候,有时候因为sql的错误耽误大量时间,所以我们可以用装饰器,来对sql进行检查,看看是否有语法错误,下面给一个简单的示例:

def check(func): def wrapper(*args, **kwargs): sql = args[0] if sql is reasonable: return func(*args, **kwargs) else: raise Exception('sql is error') return wrapper ​ ​ @check def get_sql(sql): ...

以上就是关于装饰器的内容,希望大家在工作中多多使用,刻意练习。

,

免责声明:本文仅代表文章作者的个人观点,与本站无关。其原创性、真实性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容文字的真实性、完整性和原创性本站不作任何保证或承诺,请读者仅作参考,并自行核实相关内容。文章投诉邮箱:anhduc.ph@yahoo.com

    分享
    投诉
    首页