简述python中functools.wrapper()

首先对于最简单的函数:

def a():
pass if __name__ == '__main__':
print(a.__name__)

输出结果:

a

然后稍微复杂点:

def a(func):
def wrapper()
return func @a
def b():
pass if __name__ == '__main__'
print(b.__name__)

输出结果:

a

当加上functools.wrapper时:

def a(func):
@functools.wrapper(func)
def wrapper()
return func @a
def b():
pass if __name__ == '__main__'
print(b.__name__)

输出结果:

b

很明显,通过调用functools.wrapper()使得返回值发生了改变,这其实与它的函数定义有关,代码如下:

def wraps(wrapped,
assigned = WRAPPER_ASSIGNMENTS,
updated = WRAPPER_UPDATES):
"""Decorator factory to apply update_wrapper() to a wrapper function Returns a decorator that invokes update_wrapper() with the decorated
function as the wrapper argument and the arguments to wraps() as the
remaining arguments. Default arguments are as for update_wrapper().
This is a convenience function to simplify applying partial() to
update_wrapper().
"""
return partial(update_wrapper, wrapped=wrapped,
assigned=assigned, updated=updated)
def update_wrapper(wrapper,
wrapped,
assigned = WRAPPER_ASSIGNMENTS,
updated = WRAPPER_UPDATES):
"""Update a wrapper function to look like the wrapped function wrapper is the function to be updated
wrapped is the original function
assigned is a tuple naming the attributes assigned directly
from the wrapped function to the wrapper function (defaults to
functools.WRAPPER_ASSIGNMENTS)
updated is a tuple naming the attributes of the wrapper that
are updated with the corresponding attribute from the wrapped
function (defaults to functools.WRAPPER_UPDATES)
"""
for attr in assigned:
try:
value = getattr(wrapped, attr)
except AttributeError:
pass
else:
setattr(wrapper, attr, value)
for attr in updated:
getattr(wrapper, attr).update(getattr(wrapped, attr, {}))
# Issue #17482: set __wrapped__ last so we don't inadvertently copy it
# from the wrapped function when updating __dict__
wrapper.__wrapped__ = wrapped
# Return the wrapper so this can be used as a decorator via partial()
return wrapper
class partial:
"""New function with partial application of the given arguments
and keywords.
""" __slots__ = "func", "args", "keywords", "__dict__", "__weakref__" def __new__(cls, func, /, *args, **keywords):
if not callable(func):
raise TypeError("the first argument must be callable") if hasattr(func, "func"):
args = func.args + args
keywords = {**func.keywords, **keywords}
func = func.func self = super(partial, cls).__new__(cls) self.func = func
self.args = args
self.keywords = keywords
return self def __call__(self, /, *args, **keywords):
keywords = {**self.keywords, **keywords}
return self.func(*self.args, *args, **keywords) @recursive_repr()
def __repr__(self):
qualname = type(self).__qualname__
args = [repr(self.func)]
args.extend(repr(x) for x in self.args)
args.extend(f"{k}={v!r}" for (k, v) in self.keywords.items())
if type(self).__module__ == "functools":
return f"functools.{qualname}({', '.join(args)})"
return f"{qualname}({', '.join(args)})" def __reduce__(self):
return type(self), (self.func,), (self.func, self.args,
self.keywords or None, self.__dict__ or None) def __setstate__(self, state):
if not isinstance(state, tuple):
raise TypeError("argument to __setstate__ must be a tuple")
if len(state) != 4:
raise TypeError(f"expected 4 items in state, got {len(state)}")
func, args, kwds, namespace = state
if (not callable(func) or not isinstance(args, tuple) or
(kwds is not None and not isinstance(kwds, dict)) or
(namespace is not None and not isinstance(namespace, dict))):
raise TypeError("invalid partial state") args = tuple(args) # just in case it's a subclass
if kwds is None:
kwds = {}
elif type(kwds) is not dict: # XXX does it need to be *exactly* dict?
kwds = dict(kwds)
if namespace is None:
namespace = {} self.__dict__ = namespace
self.func = func
self.args = args
self.keywords = kwds try:
from _functools import partial
except ImportError:
pass

上面大致讲的呢,就是通过调用functools.wrappers()来创建了不一样的函数,但是名字却是一样的,且id不一样,功能也可能会有所改变。代码如下:

import functools

def m(func):
print(func.__name__)
print(id(func))
@functools.wraps(func)
def wrapper():
print(wrapper.__name__)
print(id(wrapper))
return wrapper def method1():
pass @m
def method2():
print(id(method2)) if __name__ == '__main__':
print(method2())

输出:

method2
1868266070224
method2
1868266070368
None

综上:调用该函数创建了另一个名字一样的函数,但是内部构造可能会不相同。

简述python中`functools.wrapper()的更多相关文章

  1. 简述Python中的break和continue的区别

    众所周知在Python中,break是结束整个循环体,而continue则是结束本次循环再继续循环. 但是作为一个新手的你,还是不明白它们的区别,这里用一个生动的例子说明它们的区别,如下: 1.con ...

  2. Python中functools模块函数解析

    Python自带的 functools 模块提供了一些常用的高阶函数,也就是用于处理其它函数的特殊函数.换言之,就是能使用该模块对可调用对象进行处理. functools模块函数概览 functool ...

  3. python中 functools模块 闭包的两个好朋友partial偏函数和wraps包裹

    前一段时间学习了python当中的装饰器,主要利用了闭包的原理.后来呢,又见到了python当中的functools模块,里面有很多实用的功能.今天我想分享一下跟装饰器息息相关的两个函数partial ...

  4. python中functools.wraps装饰器的作用

    functools.wraps装饰器用于显示被包裹的函数的名称 import functools def node(func): #@functools.wraps(func) def wrapped ...

  5. python中functools.singledispatch的使用

    from functools import singledispatch @singledispatch def show(obj): print (obj, type(obj), "obj ...

  6. 简述python中的@staticmethod作用及用法

    关于@staticmethod,这里抛开修饰器的概念不谈,只简单谈它的作用和用法. staticmethod用于修饰类中的方法,使其可以在不创建类实例的情况下调用方法,这样做的好处是执行效率比较高.当 ...

  7. Python中表达式与语句

    简述 Python中我暂时并未发现谁对着两个名词的明确定义:我对这两个名词的理解就是,表达式就是你想要执行的对象,语句就是你的具体执行操作. 这里应用慕课网老师的一段话,摘自网上"表达式(E ...

  8. python中的functools模块

    functools模块可以作用于所有的可以被调用的对象,包括函数 定义了__call__方法的类等 1 functools.cmp_to_key(func) 将比较函数(接受两个参数,通过比较两个参数 ...

  9. Python 中实现装饰器时使用 @functools.wraps 的理由

    Python 中使用装饰器对在运行期对函数进行一些外部功能的扩展.但是在使用过程中,由于装饰器的加入导致解释器认为函数本身发生了改变,在某些情况下——比如测试时——会导致一些问题.Python 通过  ...

随机推荐

  1. Go的100天之旅-08字符串

    目录 简介 UTF-8字符 字符串的常用操作 简介 字符串在各种编程语言中都是很基础的一种类型,在Go中字符串简单理解就是一个数组,数组里面的元素是byte类型.因此基本上拥有类似数组的全部特性.例如 ...

  2. 阿里云内部超全K8s实战手册!超全127页可下载

    一直关注云计算领域的人,必定知道Docker和Kubernetes的崛起.如今,世界范围内的公有云巨头(谷歌.亚马逊.微软.华为云.阿里云等等)都在其传统的公共云服务之上提供托管的Kubernetes ...

  3. 2万字长文包教包会 JVM 内存结构 保姆级学习笔记

    写这篇的主要原因呢,就是为了能在简历上写个"熟悉JVM底层结构",另一个原因就是能让读我文章的大家也写上这句话,真是个助人为乐的帅小伙....嗯,不单单只是面向面试学习哈,更重要的 ...

  4. C++语法小记---自己实现Thread类

    自己实现Thread类 在C++的类中,普通成员函数不能作为pthread_create的线程函数,如果要作为pthread_create中的线程函数,必须是static ! 参考:https://b ...

  5. ReentrantLock以及AQS实现原理

    什么是可重入锁? ReentrantLock是可重入锁,什么是可重入锁呢?可重入锁就是当前持有该锁的线程能够多次获取该锁,无需等待.可重入锁是如何实现的呢?这要从ReentrantLock的一个内部类 ...

  6. Python数据类型-str,list常见操作

    一.字符串操作 语法:字符串名.startwith('字符串') 功能:判断字符串里是否以xxx开头 范例: 扩展:从控制台接收输入居住地址,如果地址以北京市开头,则输出北京人口,否则输入非北京人口. ...

  7. Redis的各种数据类型到底能玩出什么花儿?

    https://mp.weixin.qq.com/s/ZSQ9vCkWXYuLrKS0UJ4RIg 两个星期终于肝了出来,Redis相关问题脑图,终于整理完了!!! 文末无套路分享~~附获取方式 Re ...

  8. C# File.Exists 判断系统文件,警惕32位和64位的差异

    今天在调试一个Winform程序,使用File.Exists 判断一个已经存在的驱动文件,程序一直返回false.因为驱动文件属于系统目录,心想难道是权限不够导致的?然后用管理员身份运行软件,依然返回 ...

  9. 初学Vue.js,用 vue ui 创建项目会不会被鄙视

    全栈的自我修养: 6使用vue ui进行vue.js环境搭建 It is only with the heart that one can see rightly. What is essential ...

  10. Mysql 的数据导入导出

    一. mysqldump工具基本用法,不适用于大数据备份   1. 备份所有数据库: mysqldump -u root -p --all-databases > all_database_sq ...