Python decorators Posted on 2019-06-14 | Edited on 2019-07-16 | In python | Comments: Python 装饰器强大并且高效,这里我们只需要懂得最基础的用法。 等需要更高阶的用法时,自然会主动学习。 12345678910111213141516171819202122232425# 装饰器(decorators)# 这个例子中,beg 装饰 say# beg 会先调用 say。如果返回的 say_please 为真,beg 会改变返回的字符串。from functools import wrapsdef 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@begdef say(say_please=False): msg = "Can you buy me a beer?" return msg, say_pleaseprint(say()) # Can you buy me a beer?print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :( 参见 这里 Related Posts Numpy Note 1 Numpy Note 2 Python cheatsheet Python import 小结 Python 设置环境变量