概述:
用于管理和增强函数和类行为的代码
提供一种在函数或类定义中插入自动运行代码的机制
特点 更明确的语法、更高的代码可维护性、更好的一致性
编写
函数基础: 将函数赋给变量、将函数作为参数传递、函数嵌套及跨域访问
函数定义装饰器 通用性更好
1 """函数定义装饰器""" 2 # 通用性更好 3 4 # 参数化装饰器 5 def tags(tag): 6 def tag_decorator(func): 7 def wrapper(*args, **kwargs): 8 return f'<{tag}>{func(*args, **kwargs)}</{tag}>' 9 return wrapper 10 return tag_decorator 11 12 def p_decorator(func): 13 def wrapper(*args, **kwargs): 14 return '<p>'+func(*args, **kwargs)+'</p>' 15 16 return wrapper 17 18 def div_decorator(func): 19 def wrapper(*args, **kwargs): 20 return '<div>{}</div>'.format(func(*args, **kwargs)) 21 22 return wrapper 23 24 class Student: 25 def __init__(self, name): 26 self.name = name 27 28 @p_decorator 29 def get_name(self): 30 return self.name.upper() 31 32 @tags('p') 33 # @p_decorator 34 def get_text(): 35 return '欢迎学习优品课堂课程' 36 37 @tags('div') 38 @tags('p') 39 # @div_decorator 40 # @p_decorator 41 def get_upper_text(text): 42 return text.upper() 43 44 if __name__ == '__main__': 45 print(get_text()) 46 # < p > 欢迎学习优品课堂课程 < / p > 47 print(get_upper_text('www.codeclassroom.com')) 48 # < div > < p > WWW.CODECLASSROOM.COM < / p > < / div > 49 s = Student('Mike') 50 print(s.get_name()) 51 # < p > MIKE < / p >
类定义装饰器
装饰器参数
1 """类定义装饰器""" 2 3 4 class P: 5 def __init__(self, func): 6 self.func = func 7 8 def __call__(self, *args, **kwargs): 9 return '<p>' + self.func(*args, **kwargs) + '</p>' 10 11 class Student: 12 def __init__(self, name): 13 self.name = name 14 # @P 会出现错误 15 def get_name(self): 16 return self.name.upper() 17 18 @P 19 def get_text(): 20 return '欢迎学习优品课堂课程' 21 @P 22 def get_upper_text(text): 23 return text.upper() 24 25 26 if __name__ == '__main__': 27 print(get_text()) 28 # < p > 欢迎学习优品课堂课程 < / p > 29 print(get_upper_text('www.codeclassroom.com')) 30 # < p > WWW.CODECLASSROOM.COM < / p > 31 s = Student('John') 32 print(s.get_name()) 33 # JOHN