1. 程式人生 > >【轉】偏函式實現裝飾器的複用

【轉】偏函式實現裝飾器的複用

廖雪峰實戰中的url函式,使用偏函式,實現定義一個裝飾器就可以實現四種不同的裝飾方法。

from functools import partial

def request(path, *, method):
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kw):
            return func(*args, **kw)
        wrapper.__method__ = method.upper()
        wrapper.__route__ = path
        return wrapper
    return decorator

get = partial(request, method='get')
post = partial(request, method='post')
put = partial(request, method='put')
delete = partial(request, method='delete')