装饰器是一个函数,它可以装饰其他的函数或类并为其提供额外的功能。
GoF设计模式(在特定场景下可以复用的设计经验,一共23种经典的场景)
装饰器实现了设计模式的代理模式,用代理对象执行被代理的行为并添加额外的功能。
代理模式通常解决的都是程序横切关注功能问题(跟正常业务逻辑没有必然联系的功能)
import random
from functools import wraps
def change_return_value(func):
# 可以随时取消掉装饰器
@wraps(func)
def wrapper(*args, **kwargs):
result = func(*args, **kwargs)
# 可以跟元组,匹配任意一个即可
# if isinstance(result,(str,int)):
if type(result) == str:
result = result.title()
return result
return wrapper
# say_hello = change_return_value(say_hello)
@change_return_value
def say_hello():
return 'hello,world!'
@change_return_value
def get_num():
return random.randint(1,101)
print(say_hello())
print(get_num())
# 取消掉装饰器
say_hello = say_hello.__wrapped__
print(say_hello())
679

被折叠的 条评论
为什么被折叠?



