Home  >  Q&A  >  body text

python - 函数签名问题

def now():
    print('2016-06-03')
def log(text):
    def decorator(func):
        def wrapper(*args, **kw):
            print('%s %s():' % (text, func.__name__))
            return func(*args, **kw)
        return wrapper
    return decorator
@log('rain:')
def now():
    print('2016-06-03')
now()

像上面那样,装饰后的函数的 __name__ 已经从 now 变成了 wrapper,为什么?

ringa_leeringa_lee2742 days ago895

reply all(3)I'll reply

  • 黄舟

    黄舟2017-04-17 17:54:40

    is equivalent to now 变为 log('rain:')(原来的now)

    Then explain why __name__ is a wrapper

    According to https://docs.python.org/2.7/library/inspect.html

    __name__: name with which this function was defined

    So __name__ is based on the specific definition of time

    Like another example

    >>> def func():
    ...     pass
    ... 
    >>> new_func = func
    >>> print func.__name__
    func
    >>> print new_func.__name__
    func

    reply
    0
  • PHP中文网

    PHP中文网2017-04-17 17:54:40

    The function after decoration is actually not the now function

    But log ("rain") (now)
    is actually the wrapper you defined.

    For this problem, there is wraps in functools that can correctly set __name__ and the like

    reply
    0
  • 天蓬老师

    天蓬老师2017-04-17 17:54:40

    >>> def decorator(f):
        @functools.wraps(f)
        def wrapper(*args, **kwargs):
            return f(*args, **kwargs)
        return wrapper
    
    >>> @decorator
    def func(param1): pass
    
    >>> func.__name__
    'func'

    reply
    0
  • Cancelreply