python的装饰器详解_python 装饰器详解

前言

这篇文章打算写下关于python3中装饰器的一些认识,提高一下知识水平

1 装饰器是啥

装饰器本质上是一个 Python 函数/类,它可以让其他函数/类在不需要做任何代码修改的前提下增加额外功能,装饰器的返回值也是一个函数/类对象。它经常用于有切面需求的场景,比如:插入日志、性能测试、权限校验等场景,装饰器是解决这类问题的绝佳设计。有了装饰器,我们就可以抽离出与函数功能本身无关的代码到装饰器中复用。概括的讲,装饰器的作用就是为已经存在的对象添加额外的功能。

2 简单装饰器(不使用@符号)

下面是一个简单的装饰器例子,log_append 来装饰 direct_print,这种写法支持任意参数的direct_print,也支持任意参数的装饰函数log_append

def log_append():

def decorator(func):

def wrapper(**kwargs):

if "name" in kwargs:

print("check name %s" % (kwargs.get("name")))

else:

print("check name fail" )

return

return func(**kwargs)

return wrapper

return decorator

def direct_print(**kwargs):

print("print name is %s"% (kwargs.get("name")))

fun_decoratored=log_append()(direct_print)

fun_decoratored(names="111")

fun_decoratored(name="111")

print(fun_decoratored)

direct_print(name="111")

3 用@符号

利用@符号,可以提高代码的阅读性,我们用@的方式改写上面的代码

def log_append():

def decorator(func):

def wrapper(**kwargs):

if "name" in kwargs:

print("check name %s" % (kwargs.get("name")))

else:

print("check name fail" )

return

return func(**kwargs)

return wrapper

return decorator

@log_append()

def direct_print(**kwargs):

print("print name is %s"% (kwargs.get("name")))

direct_print(name="111")

direct_print(names="111")

4 装饰器函数传递参数并体现装饰器便利性

假如现在接口强制校验的规则不定,一个函数强制校验name,另一个强制校验names字段,后面可能还会强制校验key等别的字段,这时候改写log_append就比较方便了

下面的代码在完全不改变direct_print 业务逻辑的情况下,重写了校验逻辑,并且

复用在direct_print_names 方法

from collections import Iterable

def log_append(au_keys=[]):

def decorator(func):

def wrapper(**kwargs):

if not isinstance(au_keys,Iterable):

raise Exception("error au_keys,should be Iterable str")

for check_key in au_keys:

if check_key in kwargs:

print("check %s %s" % (check_key,kwargs.get(check_key)))

else:

print("check %s fail\n"% (check_key))

return

return func(**kwargs)

return wrapper

return decorator

@log_append(["name"])

def direct_print(**kwargs):

print("print name is %s\n"% (kwargs.get("name")))

@log_append(["names"])

def direct_print_names(**kwargs):

print("print names is %s\n"% (kwargs.get("names")))

direct_print(name="111")

direct_print(names="111")

direct_print_names(name="111")

direct_print_names(names="111")

5 functools.wraps 保留函数信息

不使用functools.wraps会导致 docstring、name这些函数元信息丢失,比如 使用 direct_print_names.name 会返回wrapper,这样很影响使用,所以我们需要functools.wraps。加入方式简单,再装饰函数传入func的地方加入@wraps

from collections import Iterable

from functools import wraps

def log_append(au_keys=[]):

def decorator(func):

@wraps(func)

def wrapper(**kwargs):

print()

if not isinstance(au_keys,Iterable):

raise Exception("error au_keys,should be Iterable str")

for check_key in au_keys:

if check_key in kwargs:

print("check %s %s" % (check_key,kwargs.get(check_key)))

else:

print("check %s fail\n"% (check_key))

return

return func(**kwargs)

return wrapper

return decorator

@log_append(["name"])

def direct_print(**kwargs):

print("print name is %s\n"% (kwargs.get("name")))

@log_append(["names"])

def direct_print_names(**kwargs):

print("print names is %s\n"% (kwargs.get("names")))

direct_print(name="111")

direct_print(names="111")

direct_print_names(name="111")

direct_print_names(names="111")

print(direct_print.__name__)

6 调用顺序

python支持多重装饰的,使用方式就是一个一个的@写下去,它的执行顺序是从外到里,最先调用最外层的装饰器,最后调用最里层的装饰器 在上面的代码里面加入打印时间的装饰函数print_time,让direct_print 先装饰print_time,direct_print_names后装饰,实际上 direct_print 效果等于

print_time(log_append(["name"])(direct_print))

direct_print_names效果等于

log_append(["_names"])(print_time(direct_print))

整体代码如下

from collections import Iterable

from functools import wraps

import time

def log_append(au_keys=[]):

def decorator(func):

@wraps(func)

def wrapper(**kwargs):

print()

if not isinstance(au_keys,Iterable):

raise Exception("error au_keys,should be Iterable str")

for check_key in au_keys:

if check_key in kwargs:

print("check %s %s" % (check_key,kwargs.get(check_key)))

else:

print("check %s fail\n"% (check_key))

return

return func(**kwargs)

return wrapper

return decorator

def print_time(func):

@wraps(func)

def wrapper(**kwargs):

print("time is %s"%(time.strftime("%Y-%m-%d %H:%M;%S",time.localtime())))

return func(**kwargs)

return wrapper

@print_time

@log_append(["name"])

def direct_print(**kwargs):

print("print name is %s\n"% (kwargs.get("name")))

@log_append(["names"])

@print_time

def direct_print_names(**kwargs):

print("print names is %s\n"% (kwargs.get("names")))

direct_print(name="111")

direct_print(names="111")

direct_print_names(name="111")

direct_print_names(names="111")

print(direct_print.__name__)

结语

这篇文章看下来,python的装饰器基本上差不多了吧,好好学习,天天向上 ^_^

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值