gpt4 book ai didi

Python functools.wraps 等价于类

转载 作者:IT老高 更新时间:2023-10-28 21:39:59 29 4
gpt4 key购买 nike

使用类定义装饰器时,如何自动传递__name____module____doc__?通常,我会使用来自 functools 的 @wraps 装饰器。这是我为一个类所做的(这不完全是我的代码):

class memoized:
"""Decorator that caches a function's return value each time it is called.
If called later with the same arguments, the cached value is returned, and
not re-evaluated.
"""
def __init__(self, func):
super().__init__()
self.func = func
self.cache = {}

def __call__(self, *args):
try:
return self.cache[args]
except KeyError:
value = self.func(*args)
self.cache[args] = value
return value
except TypeError:
# uncacheable -- for instance, passing a list as an argument.
# Better to not cache than to blow up entirely.
return self.func(*args)

def __repr__(self):
return self.func.__repr__()

def __get__(self, obj, objtype):
return functools.partial(self.__call__, obj)

__doc__ = property(lambda self:self.func.__doc__)
__module__ = property(lambda self:self.func.__module__)
__name__ = property(lambda self:self.func.__name__)

是否有标准的装饰器来自动创建名称模块和文档?另外,为了自动化 get 方法(我假设那是为了创建绑定(bind)方法?)是否缺少任何方法?

最佳答案

似乎每个人都错过了明显的解决方案。使用 functools.update_wrapper :

>>> import functools
>>> class memoized(object):
"""Decorator that caches a function's return value each time it is called.
If called later with the same arguments, the cached value is returned, and
not re-evaluated.
"""
def __init__(self, func):
self.func = func
self.cache = {}
functools.update_wrapper(self, func) ## TA-DA! ##
def __call__(self, *args):
pass # Not needed for this demo.

>>> @memoized
def fibonacci(n):
"""fibonacci docstring"""
pass # Not needed for this demo.

>>> fibonacci
<__main__.memoized object at 0x0156DE30>
>>> fibonacci.__name__
'fibonacci'
>>> fibonacci.__doc__
'fibonacci docstring'

关于Python functools.wraps 等价于类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6394511/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com