帶有參數的裝飾器

一個帶有參數的裝飾器的例子:python

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中自動轉換參數類型的裝飾器:app

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")
相關文章
相關標籤/搜索