Discuss / Python / 装饰器(带参数,不带参数)

装饰器(带参数,不带参数)

Topic source
import time, functools

#The firston question

def metric(fn):
    def wrapper (*args, **kw):
        t0=time.time()
        fn(*args,**kw)
        t1=time.time()
        print('%s executed in %s ms' % (fn.__name__, (t1-t0)* 1000))
        return fn
    return wrapper

#The second question

def bcall(fn):
    def wrapper(*args,**kw):
        print('Begin call')
        fn(*args,*kw)
        print('End call')
        return fn
    return wrapper

#The third question

def log(text):
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kw):
            if isinstance(text, str):
                print('Begin %s %s():' % (text, func.__name__))
            else:print('Begin call %s():' % func.__name__)
            func(*args, **kw)
            print('End call')
            return func
        return wrapper
    if callable(text):
        return decorator(text)
    else:
        return decorator

测试程序

@log

def f(): print('不带参数程序运行内容')

@log('execute')

def f1(): print('带参数程序运行内容')

f() f1()

输出结果

Begin call f(): 不带参数程序运行内容 End call Begin execute f1(): 带参数程序运行内容 End call*

没测试完整,返回数值不正常,现更正:

The first question

def metric(fn):
    @functools.wraps(fn)
    def wrapper (*args, **kw):
        t0=time.time()
        back=fn(*args,**kw)
        t1=time.time()
        print('%s executed in %s ms' % (fn.__name__, (t1-t0)* 1000))
        return back
    return wrapper

The second question

def bcall(fn):
    @functools.wraps(fn)
    def wrapper(*args,**kw):
        print('Begin call')
        back=fn(*args,*kw)
        print('End call')
        return back
    return wrapper

The third question

ef metric(text):
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kw):
            if isinstance(text, str):
                print('Begin %s %s():' % (text, func.__name__))
            else:print('Begin call %s():' % func.__name__)
            back=func(*args, **kw)
            print('End call')
            return back
        return wrapper
    if callable(text):
        return decorator(text)
    else:
        return decorator

  • 1

Reply