带有参数的装饰器

一个带有参数的装饰器的例子:

def decrator(*dargs, **dkargs):
    def wrapper(func):
        def _wrapper(*args, **kargs):
            print "decrator param:", dargs, dkargs
            print "function param:", args, kargs
            return func(*args, **kargs)
        return _wrapper
    return wrapper

@decrator(1, a=2)
def foo(x, y=0):
    print "foo", x, y

foo(3, y=4)

# 输出:
# decrator param: (1,) {'a': 2}
# function param: (3,) {'y': 4}
# foo 3 4

 bottle.py中自动转换参数类型的装饰器:

def validate(**vkargs):
    def decorator(func):
        def wrapper(**kargs):
            for key in vkargs:
                # 根据vkargs中的参数的类型对kargs的参数进行类型转换
                kargs[key] = vkargs[key](kargs[key])
            return func(**kargs)
        return wrapper
    return decorator


@validate(id=int, x=float, y=float)
def move(id, x, y):
    print "move %d (%0.2f, %0.2f)"%(id, x, y)

move(id="1", x="0.2", y="0.3")

 

posted @ 2017-02-06 10:24  鸪斑兔  阅读(1807)  评论(0编辑  收藏  举报