相关疑难解决方法(0)

functools.wraps有什么作用?

对另一个问题的答案的评论中,有人说他们不确定functools.wraps在做什么.所以,我问这个问题,以便在StackOverflow上有一个记录,供将来参考:究竟functools.wraps做了什么?

python decorator functools

588
推荐指数
6
解决办法
12万
查看次数

Python functools.wraps等同于类

使用类定义装饰器时,如何自动转移__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 …
Run Code Online (Sandbox Code Playgroud)

python decorator

69
推荐指数
4
解决办法
2万
查看次数

如何复制python类?

deepcopycopy不会复制一个类:

>>> class A(object):
>>>     ARG = 1

>>> B = deepcopy(A)

>>> A().ARG
>>> 1

>>> B().ARG
>>> 1

>>> A.ARG = 2

>>> B().ARG
>>> 2
Run Code Online (Sandbox Code Playgroud)

这是唯一的方式吗?

B(A):
    pass
Run Code Online (Sandbox Code Playgroud)

python

47
推荐指数
4
解决办法
5万
查看次数

标签 统计

python ×3

decorator ×2

functools ×1