Discuss / Python / 感觉是最容易懂的方法,不知道还能不能优化

感觉是最容易懂的方法,不知道还能不能优化

Topic source

Pop_林肥強

#1 Created at ... [Delete] [Delete and Lock User]
# 编写一个decorator,能在函数调用的前后打印出'begin call'和'end call'的日志。
import functools


def log(text):
    if isinstance(text, str):

        def decorator(func):
            functools.wraps(func)

            def wrapper(*args, **kw):
                print('%s begin call : %s' % (text, func.__name__))
                func(*args, **kw)
                print('%s end call : %s' % (text, func.__name__))

            return wrapper

        return decorator
    else:
        func = text
        functools.wraps(func)

        def wrapper(*args, **kw):
            print('begin call : %s' % func.__name__)
            text(*args, **kw)
            print('end call : %s' % func.__name__)

        return wrapper


@log
def f():
    print('不带参数')


@log('excute')
def f():
    print('带参数')


f()

青酱酱君

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

请问为什么要func = text呢?text不是空值吗?

哥们我只服你

李D华

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

这个是正解!茅塞顿开!谢谢了!


  • 1

Reply