Decorator in Python
2016-03-18 本文已影响0人
Infoceiver
First look at what a decorator code really is doing.
The following two blocks of code are same:
@dec
def func():
pass
and
def func():
pass
func = dec(func)
Where dec is pre-defined function:
def dec(f):
def wrapped(*args, **kwargs):
pass # wrapped has f and args pass to f;
# may call f() and do something else
return wrapped
So when you evoke the function func, what is really call is wrapped function produced by dec, and args will be pass to new function wrapped and also original function func will get involved in wrapped.
The purpose of the decorator is to customize or decorate a set of the functions when you define them so that the function decorated will share some common operations. The decorated function will do what is designed to do by decorator, instead of only finishing what this function is designed to do.
Few Examples (common usages)
HTML
def p_decorate(func):
def func_wrapper(name):
return "<p>{0}</p>".format(func(name))
return func_wrapper
def strong_decorate(func):
def func_wrapper(name):
return "<strong>{0}</strong>".format(func(name))
return func_wrapper
def div_decorate(func):
def func_wrapper(name):
return "<div>{0}</div>".format(func(name))
return fun_wrapper
@div_decorate
@p_decorate
@strong_decorate
def get_text(name):
return "lorem ipsum, {0} dolor sit amet".format(name)
print get_text("John")
# Outputs <div><p><strong>lorem ipsum, John dolor sit amet</strong></p></div>
Decorator Function (passing args to decorator)
def tags(tag_name):
def tags_decorator(func):
def func_wrapper(name):
return "<{0}>{1}</{0}>".format(tag_name, func(name))
return func_wrapper
return tags_decorator
@tags("p")
def get_text(name):
return "Hello "+name
print get_text("John")
# Outputs <p>Hello John</p>