Discuss / Python / 参考了一些同学的答案,写下自己的理解

参考了一些同学的答案,写下自己的理解

Topic source

飞侠100

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

理解这个问题的关键是,如果装饰器是@log('execute'),那么第一层函数log的参数text的值为'execure',第二层函数decorator的参数func的值为函数now;如果装饰器是@log,那么参数text的值为now,此时也就不需要第二层函数decorator了。

很多同学被text的名字所误导了,以为只能接收字符串作为参数。当你明白text既可以是字符串'execute'也可以是函数now的时候,你就知道这个问题怎么解决了。


def log(text):
    if isinstance(text, str):
        def decorator(func):
            @functools.wraps(func)
            def wrapper(*args, **kw):
                print('The text is: %s' % text)
                print('begin call')
                a = func(*args, **kw)
                print('end call')
                return a
            return wrapper
        return decorator
    else:
        @functools.wraps(text)
        def wrapper(*args, **kw):
            print('begin call')
            a = text(*args, **kw)
            print('end call')
            return a
        return wrapper

  • 1

Reply