Discuss / Python / @log @(text)

@log @(text)

Topic source

最帅的仔

#1 Created at ... [Delete] [Delete and Lock User]
import time, functools

def log(arg):
    flag = isinstance(arg, str)
    def inner(func):
        @functools.wraps(func)
        def wrapper(*args, **kw):
            start = time.time()
            if flag: 
                print('%s %s():' % (arg, func.__name__))
            else:
                print('call %s():' % func.__name__)
            ret = func(*args, **kw)
            print(f'用时{time.time() - start}')
            print('--------------')
            return ret
        return wrapper
    return  inner if flag else inner(arg)


@log('传参调用了装饰器')
def testLog(*args, **kw):
    print(*args, **kw)
    print('testLog')

testLog(1,2)
@log
def now(*args, **kw):
    print(*args, **kw)
    print('now')
now(1,2)

# 输出如下:
# 传参调用了装饰器 testLog():
# 1 2
# testLog
# 用时0.000965118408203125 
# --------------
# call now():
# 1 2
# now
# 用时0.0009965896606445312
# --------------

最帅的仔

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

感觉不是很完善,请大神补充下


  • 1

Reply