博客
关于我
Python 中 functools.wraps 简介
阅读量:363 次
发布时间:2019-03-04

本文共 1083 字,大约阅读时间需要 3 分钟。

在人类世界中有一些大佬,经过细心装扮之后,自身的属性可以变得让人雌雄莫辨。(我没有在说 Abbily,我是在说花木兰!)

Python 世界中也是一样,一些函数经过装饰器的悉心装饰之后,一些属性也会变得令人迷惑。

先定义一个啥都不干,但很淳朴的函数,顺便看看它的函数名和文档字符串:

def iron_egg():    """我是铁蛋儿~"""    returnprint(iron_egg.__name__)print(iron_egg.__doc__)"""输出:iron_egg我是铁蛋儿~"""

再定义一个啥都不干,但很美丽的装饰器:

def decorator(func):    def spring_blossom(*args, **kwargs):        """我是春花儿~"""        return func(*args, **kwargs)    return spring_blossom

手动用美丽的装饰器装饰一下淳朴的函数,然后再检查一下函数名和文档字符串:

iron_egg = decorator(iron_egg)print(iron_egg.__name__)print(iron_egg.__doc__)"""spring_blossom我是春花儿~"""

可见在装饰器的作用下,铁蛋儿变成了春花儿,这大多数情况下并不是我们想要的行为。

如何保持函数的本来面目呢?可以使用 functools 模块提供的 wraps 装饰器。

from functools import wrapsdef decorator(func):    @wraps(func)    def spring_blossom(*args, **kwargs):        """我是春花儿~"""        return func(*args, **kwargs)    return spring_blossom@decoratordef iron_egg():    """我是铁蛋儿~"""    returnprint(iron_egg.__name__)print(iron_egg.__doc__)"""iron_egg我是铁蛋儿~"""

可见,在 @wraps(func) 的帮助下,铁蛋儿还是铁蛋儿,它拒绝了女装,果然不负众望。(你很失望?你不对劲儿!)

那么 functools.wraps 这个东西为何如此神奇?实际上它用到了 functools 中的另外一个 partial 函数,这就留待下回分解吧!

转载地址:http://fscr.baihongyu.com/

你可能感兴趣的文章
nnU-Net 终极指南
查看>>
No 'Access-Control-Allow-Origin' header is present on the requested resource.
查看>>
No 'Access-Control-Allow-Origin' header is present on the requested resource.
查看>>
NO 157 去掉禅道访问地址中的zentao
查看>>
no available service ‘default‘ found, please make sure registry config corre seata
查看>>
No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?
查看>>
no connection could be made because the target machine actively refused it.问题解决
查看>>
No Datastore Session bound to thread, and configuration does not allow creation of non-transactional
查看>>
No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
查看>>
No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-loadbalanc
查看>>
No mapping found for HTTP request with URI [/...] in DispatcherServlet with name ...的解决方法
查看>>
No mapping found for HTTP request with URI [/logout.do] in DispatcherServlet with name 'springmvc'
查看>>
No module named 'crispy_forms'等使用pycharm开发
查看>>
No module named cv2
查看>>
No module named tensorboard.main在安装tensorboardX的时候遇到的问题
查看>>
No module named ‘MySQLdb‘错误解决No module named ‘MySQLdb‘错误解决
查看>>
No new migrations found. Your system is up-to-date.
查看>>
No qualifying bean of type XXX found for dependency XXX.
查看>>
No qualifying bean of type ‘com.netflix.discovery.AbstractDiscoveryClientOptionalArgs<?>‘ available
查看>>
No resource identifier found for attribute 'srcCompat' in package的解决办法
查看>>