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

membalas semua(3)
黄舟

等价于 now 变为 log('rain:')(原来的now)

然后解释下为啥__name__是wrapper

根据https://docs.python.org/2.7/library/inspect.html

__name__: name with which this function was defined

所以__name__是根据具体定义时候的来

如另外一个例子

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

装饰之后的函数其实不是now函数了

而是log(“rain”)(now)
其实就是你定义的wrapper。

对于这个问题、functools里有个wraps可以把__name__之类的正确设置

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'
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan