Python functools.wraps equivalent for classes

前端 未结 5 1695
予麋鹿
予麋鹿 2020-12-04 09:13

When defining a decorator using a class, how do I automatically transfer over__name__, __module__ and __doc__? Normally, I would use

5条回答
  •  难免孤独
    2020-12-04 09:53

    Everyone seems to have missed the obvious solution.

    >>> 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'
    

提交回复
热议问题