脚本宝典收集整理的这篇文章主要介绍了装饰器模式学习,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
转自:https://www.runoob.COM/design-pattern/decorator-pattern.htML
@H_304_2@1.介绍优点:装饰类和被装饰类可以独立发展,不会相互耦合,装饰模式是继承的一个替代模式,装饰模式可以动态扩展一个实现类的功能。
缺点:多层装饰比较复杂。
上述链接中给的例子很好。组件类为图形类,有一个抽象类Shape,两个图形子类Circle和Rect,那么抽象装饰类继承了ShaPE,并且有一个shape类对象,可以实现Set不同的类对象,从而实现对不同shape的装饰;实现了装饰红色red的具体装饰类,并且都实现了draw方法,这样在draw时具体装饰类可以做出不同的动作。
https://www.runoob.com/w3cnote/python-func-decorators.html
From functools import wraps def a_new_decorator(a_func): @wraps(a_func) def wrapTheFunction(): PRint("I am doing some boring work before executing a_func()") a_func() print("I am doing some boring work after executing a_func()") return wrapTheFunction @a_new_decorator def a_function_requiring_decoration(): """Hey yo! Decorate me!""" print("I am the function which needs some decoration to " "remove my foul smell") print(a_function_requiring_decoration.__name__) # Output: a_function_requiring_decoration
那么这样在调用a_function_requiring_decoration()前,会先调用a_new_decorator(),wraps函数接受一个函数来进行装饰,并加入了复制函数名称、注释文档、参数列表等等的功能。这可以让我们在装饰器里面访问在装饰之前的函数的属性。
装饰器能有助于检查某个人是否被授权去使用一个web应用的端点(endpoint)。它们被大量使用于Flask和Django web框架中。这里是一个例子来使用基于装饰器的授权:
from functools import wraps def requires_auth(f): @wraps(f) def decorated(*args, **kwargs): auth = request.authorization if not auth or not check_auth(auth.username, auth.password): authenticate() return f(*args, **kwargs) return decorated
日志,通过带参数的装饰器,写入到不同的文件中。
以上是脚本宝典为你收集整理的装饰器模式学习全部内容,希望文章能够帮你解决装饰器模式学习所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。