defcompose_greet_func(name):defget_message():return"Hello there "+name+"!"returnget_messagegreet=compose_greet_func("John")printgreet()# Outputs: Hello there John!
defline_conf():b=15defline(x):return2*x+breturnline# return a function objectb=5my_line=line_conf()# 返回一个闭包函数print(my_line(5))
构造装饰器
函数装饰器就是已存在函数的一个包装器。我们把上面的这些结合起来就能构建一个装饰器了。
下面例子中我们先构造一个函数来用p标签包装其他函数返回的一个字符串。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
defget_text(name):return"lorem ipsum, {0} dolor sit amet".format(name)defp_decorate(func):deffunc_wrapper(name):return"<p>{0}</p>".format(func(name))returnfunc_wrappermy_get_text=p_decorate(get_text)printmy_get_text("John")# <p>Outputs lorem ipsum, John dolor sit amet</p>
defp_decorate(func):deffunc_wrapper(name):return"<p>{0}</p>".format(func(name))returnfunc_wrapper@p_decoratedefget_text(name):return"lorem ipsum, {0} dolor sit amet".format(name)printget_text("John")# Outputs <p>lorem ipsum, John dolor sit amet</p>
@div_decorate@p_decorate@strong_decoratedefget_text(name):return"lorem ipsum, {0} dolor sit amet".format(name)printget_text("John")# Outputs <div><p><strong>lorem ipsum, John dolor sit amet</strong></p></div>
fromfunctoolsimportwrapsdeftags(tag_name):deftags_decorator(func):@wraps(func)deffunc_wrapper(*args,**kargs):return"<{0}>{1}</{0}>".format(tag_name,func(*args,**kargs))returnfunc_wrapperreturntags_decoratordefpptags(func):@wraps(func)deffunc_wrapper(*args,**kargs):return"<{0}>{1}</{0}>".format('pp',func(*args,**kargs))returnfunc_wrapper@tags('p')defget_text(name):"""returns some text with p"""return"Hello "+name@pptagsdefget_text_pp(name):"""returns some text with pp"""return"Hello "+nameif__name__=='__main__':print(get_text.__name__)# get_textprint(get_text.__doc__)# returns some textprint(get_text.__module__)# __main__print(get_text('韩梅梅'))print(get_text_pp.__name__)# get_textprint(get_text_pp.__doc__)# returns some textprint(get_text_pp.__module__)# __main__print(get_text_pp('李雷'))