Discuss / Python / 答案

答案

Topic source

Time_liar

#1 Created at ... [Delete] [Delete and Lock User]
"""
input "None"
"""
import functools


def log(text=None):
    def decorator(func=None):

        @functools.wraps(func)
        def wrapper(*args, **kw):
            print('Begin Call')
            if text is not None:
                print('%s: %s()' % (text, func.__name__))
            else:
                print('Call: %s()' % func.__name__)
            r = func(*args, **kw)
            print('End Call')
            return r

        return wrapper

    return decorator


@log()
def now():
    print('2016-1-11')


@log('Execute')
def yesterday():
    print('2016-1-10')


if __name__ == '__main__':
    now()
    print('')
    yesterday()
Begin Call
Call: now()
2016-1-11
End Call

Begin Call
Execute: yesterday()
2016-1-10
End Call

郭翼藤

#2 Created at ... [Delete] [Delete and Lock User]

虽然我测试了发现这个答案是对的但是有一点很矛盾啊。 当你调用没有参数的的log时

@log()
def now():
    print('2016-1-11')
.
.
.
.
now()

这时候now()应该可以被看作

now = log(now)
now()

那按照log函数所看,这个时候text就被赋值为now了,而不是func被赋值为now(这个时候应该func默认为None了)

但是这个程序的确是可以运行并且是成功的,这是为什么……

我理解的是这种写法如果调用无参@log

@log()
def now():
....

应该是类似于

log()(now)

不知道我理解的对不对

我感觉log()(now)这个理解非常到位!


  • 1

Reply