python - 函数签名问题
ringa_lee
ringa_lee 2017-04-17 17:52:40
0
3
915
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_lee
ringa_lee

ringa_lee

reply all(3)
黄舟

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
洪涛

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

Peter_Zhu
>>> def decorator(f):
    @functools.wraps(f)
    def wrapper(*args, **kwargs):
        return f(*args, **kwargs)
    return wrapper

>>> @decorator
def func(param1): pass

>>> func.__name__
'func'
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template