Python decorators

Python 装饰器强大并且高效,这里我们只需要懂得最基础的用法。 等需要更高阶的用法时,自然会主动学习。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# 装饰器(decorators)
# 这个例子中,beg 装饰 say
# beg 会先调用 say。如果返回的 say_please 为真,beg 会改变返回的字符串。
from functools import wraps


def beg(target_function):
@wraps(target_function)
def wrapper(*args, **kwargs):
msg, say_please = target_function(*args, **kwargs)
if say_please:
return "{} {}".format(msg, "Please! I am poor :(")
return msg

return wrapper


@beg
def say(say_please=False):
msg = "Can you buy me a beer?"
return msg, say_please


print(say()) # Can you buy me a beer?
print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :(

参见 这里