Python 装饰模式讲解和代码示例

简介: Python 装饰模式讲解和代码示例

使用示例装饰在 Python 代码中可谓是标准配置 尤其是在与流式加载相关的代码中

识别方法装饰可通过以当前类或对象为参数的创建方法或构造函数来识别

概念示例

本例说明了装饰设计模式的结构并重点回答了下面的问题

  • 它由哪些类组成
  • 这些类扮演了哪些角色
  • 模式中的各个元素会以何种方式相互关联

main.py: 概念示例

class Component():    """    The base Component interface defines operations that can be altered by    decorators.    """
    def operation(self) -> str:        passclass ConcreteComponent(Component):    """    Concrete Components provide default implementations of the operations. There    might be several variations of these classes.    """
    def operation(self) -> str:        return "ConcreteComponent"class Decorator(Component):    """    The base Decorator class follows the same interface as the other components.    The primary purpose of this class is to define the wrapping interface for    all concrete decorators. The default implementation of the wrapping code    might include a field for storing a wrapped component and the means to    initialize it.    """
    _component: Component = None
    def __init__(self, component: Component) -> None:        self._component = component
    @property
    def component(self) -> Component:        """        The Decorator delegates all work to the wrapped component.        """
        return self._component
    def operation(self) -> str:        return self._component.operation()class ConcreteDecoratorA(Decorator):    """    Concrete Decorators call the wrapped object and alter its result in some    way.    """
    def operation(self) -> str:        """        Decorators may call parent implementation of the operation, instead of        calling the wrapped object directly. This approach simplifies extension        of decorator classes.        """
        return f"ConcreteDecoratorA({self.component.operation()})"class ConcreteDecoratorB(Decorator):    """    Decorators can execute their behavior either before or after the call to a    wrapped object.    """
    def operation(self) -> str:        return f"ConcreteDecoratorB({self.component.operation()})"def client_code(component: Component) -> None:    """    The client code works with all objects using the Component interface. This    way it can stay independent of the concrete classes of components it works    with.    """
    # ...
    print(f"RESULT: {component.operation()}", end="")    # ...if __name__ == "__main__":    # This way the client code can support both simple components...
    simple = ConcreteComponent()    print("Client: I've got a simple component:")    client_code(simple)    print("\n")    # ...as well as decorated ones.
    #
    # Note how decorators can wrap not only simple components but the other
    # decorators as well.
    decorator1 = ConcreteDecoratorA(simple)    decorator2 = ConcreteDecoratorB(decorator1)    print("Client: Now I've got a decorated component:")    client_code(decorator2)

Output.txt: 执行结果

Client: I've got a simple component:
RESULT: ConcreteComponent
Client: Now I've got a decorated component:
RESULT: ConcreteDecoratorB(ConcreteDecoratorA(ConcreteComponent))
相关文章
|
3月前
|
开发框架 数据建模 中间件
Python中的装饰器:简化代码,增强功能
在Python的世界里,装饰器是那些静悄悄的幕后英雄。它们不张扬,却能默默地为函数或类增添强大的功能。本文将带你了解装饰器的魅力所在,从基础概念到实际应用,我们一步步揭开装饰器的神秘面纱。准备好了吗?让我们开始这段简洁而富有启发性的旅程吧!
59 6
|
5天前
|
Go Python
Python中的round函数详解及使用示例
`round()`函数是Python内置的用于四舍五入数字的工具。它接受一个数字(必需)和可选的小数位数参数,返回最接近的整数或指定精度的浮点数。本文详细介绍其用法、参数及示例,涵盖基本操作、负数处理、特殊情况及应用建议,帮助你更好地理解和运用该函数。
|
5天前
|
数据采集 供应链 API
实战指南:通过1688开放平台API获取商品详情数据(附Python代码及避坑指南)
1688作为国内最大的B2B供应链平台,其API为企业提供合法合规的JSON数据源,直接获取批发价、SKU库存等核心数据。相比爬虫方案,官方API避免了反爬严格、数据缺失和法律风险等问题。企业接入1688商品API需完成资质认证、创建应用、签名机制解析及调用接口四步。应用场景包括智能采购系统、供应商评估模型和跨境选品分析。提供高频问题解决方案及安全合规实践,确保数据安全与合法使用。立即访问1688开放平台,解锁B2B数据宝藏!
|
5天前
|
API 开发工具 Python
【Azure Developer】编写Python SDK代码实现从China Azure中VM Disk中创建磁盘快照Snapshot
本文介绍如何使用Python SDK为中国区微软云(China Azure)中的虚拟机磁盘创建快照。通过Azure Python SDK的Snapshot Class,指定`location`和`creation_data`参数,使用`Copy`选项从现有磁盘创建快照。代码示例展示了如何配置Default Azure Credential,并设置特定于中国区Azure的`base_url`和`credential_scopes`。参考资料包括官方文档和相关API说明。
|
2月前
|
存储 缓存 Java
Python高性能编程:五种核心优化技术的原理与Python代码
Python在高性能应用场景中常因执行速度不及C、C++等编译型语言而受质疑,但通过合理利用标准库的优化特性,如`__slots__`机制、列表推导式、`@lru_cache`装饰器和生成器等,可以显著提升代码效率。本文详细介绍了这些实用的性能优化技术,帮助开发者在不牺牲代码质量的前提下提高程序性能。实验数据表明,这些优化方法能在内存使用和计算效率方面带来显著改进,适用于大规模数据处理、递归计算等场景。
73 5
Python高性能编程:五种核心优化技术的原理与Python代码
|
2月前
|
数据挖掘 数据处理 开发者
Python3 自定义排序详解:方法与示例
Python的排序功能强大且灵活,主要通过`sorted()`函数和列表的`sort()`方法实现。两者均支持`key`参数自定义排序规则。本文详细介绍了基础排序、按字符串长度或元组元素排序、降序排序、多条件排序及使用`lambda`表达式和`functools.cmp_to_key`进行复杂排序。通过示例展示了如何对简单数据类型、字典、类对象及复杂数据结构(如列车信息)进行排序。掌握这些技巧可以显著提升数据处理能力,为编程提供更强大的支持。
40 10
|
3月前
|
Python
课程设计项目之基于Python实现围棋游戏代码
游戏进去默认为九路玩法,当然也可以选择十三路或是十九路玩法 使用pycharam打开项目,pip安装模块并引用,然后运行即可, 代码每行都有详细的注释,可以做课程设计或者毕业设计项目参考
85 33
|
3月前
|
JavaScript API C#
【Azure Developer】Python代码调用Graph API将外部用户添加到组,结果无效,也无错误信息
根据Graph API文档,在单个请求中将多个成员添加到组时,Python代码示例中的`members@odata.bind`被错误写为`members@odata_bind`,导致用户未成功添加。
59 10
|
3月前
|
数据可视化 Python
以下是一些常用的图表类型及其Python代码示例,使用Matplotlib和Seaborn库。
通过这些思维导图和分析说明表,您可以更直观地理解和选择适合的数据可视化图表类型,帮助更有效地展示和分析数据。
114 8
|
3月前
|
API Python
【Azure Developer】分享一段Python代码调用Graph API创建用户的示例
分享一段Python代码调用Graph API创建用户的示例
74 11

热门文章

最新文章