ITPub博客

首页 > > > 一文搞懂python中最强大的装饰器,并附加应用实例

一文搞懂python中最强大的装饰器,并附加应用实例

作者:25minutes 时间:2019-08-09 11:04:37 0 删除 编辑

趣谈数据分析 


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

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的使用,在这里就不再赘述了,我之前的文章中有详细的介绍。

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

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

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):

...

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

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/4328/viewspace-3147161/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-07-17

  • 博文量
    336
  • 访问量
    14896