Python 装饰器模式

# -*- coding: utf-8 -*-
"""
Created on Sat Feb 24 11:37:17 2018

@author: mz
"""

class Warrior:
    def __init__(self):        
        self.attrack = 100
        self.defend = 200   
        
    def ShowAttributes(self):
        print("*self*")
        print("attrack : %d" % (self.attrack) )
        print("attrack : %d \r\n" % (self.defend) )
        

class OnCloth(Warrior):
    def __init__(self, rhs):
        self.attrack = 100+ rhs.attrack
        self.defend  = 300+ rhs.defend
    
    def ShowAttributes(self):
        print("*on cloth*")
        print("attrack : %d" %(self.attrack))
        print("attrack : %d \r\n" %(self.defend) )
    
        
class OnWeapon(Warrior):
    def __init__(self, rhs):
        self.attrack = 1500 + rhs.attrack
        self.defend  = 100  + rhs.defend
    
    def ShowAttributes(self):
        print("*on weapon*")
        print("attrack : %d " %(self.attrack))
        print("attrack : %d \r\n" %(self.defend))

if "__main__" == __name__:
    print("crete a warrior....")
    person = Warrior()
    person.ShowAttributes()
    
    print("put on cloth....")
    putonCloth = OnCloth(person);
    person.ShowAttributes();
    putonCloth.ShowAttributes();
    
    print("put on weapon....")
    holdWeapon = OnWeapon(putonCloth);
    person.ShowAttributes();
    putonCloth.ShowAttributes();
    holdWeapon.ShowAttributes();

装饰模式,经过装饰后总的属性发生变化,但是本身属性不发生变化, 输出结果:

crete a warrior....
*self*
attrack : 100
attrack : 200 

put on cloth....
*self*
attrack : 100
attrack : 200 

*on cloth*
attrack : 200
attrack : 500 

put on weapon....
*self*
attrack : 100
attrack : 200 

*on cloth*
attrack : 200
attrack : 500 

*on weapon*
attrack : 1700 
attrack : 600 
Python中的装饰器模式(Decorator Pattern)是一种设计模式,旨在动态地为对象添加额外的责任或功能。与传统的继承机制相比,装饰器模式提供了更灵活、可组合的方式来扩展对象的行为,而无需修改其源代码 [^1]。 在Python中,装饰器本质上是一个函数,用于包装另一个函数或类,并对其进行增强。装饰器的核心思想是通过闭包和高阶函数实现对现有函数的透明扩展。装饰器的基本形式可以理解为:一个接受函数作为参数并返回新函数的可调用对象。 ### 装饰器的基本语法 Python 提供了简洁的语法糖 `@decorator` 来应用装饰器。例如: ```python @my_decorator def my_function(): pass ``` 该写法等价于以下表达式: ```python my_function = my_decorator(my_function) ``` 如果装饰器是一个类,则需要确保它能够接收被装饰的函数作为参数,并且该类实例必须是可调用的,通常通过实现 `__call__` 方法来实现 [^2]。 ### 简单示例 下面是一个简单的装饰器示例,展示如何记录函数的执行时间: ```python import time def timer(func): def wrapper(*args, **kwargs): start_time = time.time() result = func(*args, **kwargs) end_time = time.time() print(f"Function {func.__name__} took {end_time - start_time:.4f} seconds") return result return wrapper @timer def example_function(): time.sleep(1) example_function() ``` 在这个例子中,`timer` 是一个装饰器函数,它包裹了 `example_function` 并为其添加了计时的功能。 ### 类作为装饰器 除了使用函数作为装饰器,也可以使用类来实现。例如: ```python class MyDecorator: def __init__(self, func): self.func = func def __call__(self, *args, **kwargs): print("Before function call") result = self.func(*args, **kwargs) print("After function call") return result @MyDecorator def say_hello(): print("Hello") say_hello() ``` 上述代码中,`MyDecorator` 是一个类,它实现了 `__init__` 和 `__call__` 方法。通过这种方式,类装饰器能够保持状态并提供更复杂的逻辑。 ### 常见用途 装饰器广泛应用于日志记录、性能监控、权限检查、缓存、输入验证等领域。Python 社区还维护了一个包含大量装饰器示例的 Python Decorator Library,尽管它缺乏系统化的组织和详细解释 [^3]。 ### 学习资源 对于希望深入学习装饰器的人,可以从官方文档以及社区提供的教程入手。此外,还可以查阅关于 Python 新增功能的内容,了解语言特性演进的历史背景,如 Python 3.3 中引入的 `yield from` 和 Python 3.6 的异步生成器等 [^4]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值