Python中的Decorators表面看起来很像C#的Attribute,其实不然,Python的Decorators和C#的Attribute完全是两个东西。Python的Decorators让我想到了设计模式中的装饰者模式(Decorator Pattern)。

Decorator Pattern

Attach additional responsibilities to an object dynamically.
Decorators provide a flexible alternative to subclassing for extending functionnality.

Python中的通过Decorators对函数、方法或类进行装饰,从而达到增加对象的职责,或控制对象调用的作用。而C#的Attribute仅仅是起到元数据标识作用,最终通过反射获取这些特定信息。

先来个简单的示例,先定义一个Coffee类,

class Coffee(object):
    
def get_cost(self):
        
return 1.0

coffee 
= Coffee()
print coffee.get_cost() # 1.0

这时,我想通过装饰者模式计算Milk的价格,通常这样实现:

class Milk(Coffee):
    
def __init__(self, coffee):
        self.coffee 
= coffee
 
    
def get_cost(self):
        
return self.coffee.get_cost() + 0.5

coffee 
= Coffee()
coffee 
= Milk(coffee)
print coffee.get_cost() # 1.5

相关文章:

  • 2021-12-27
  • 2021-06-13
  • 2021-10-07
  • 2022-01-28
  • 2022-02-13
  • 2021-05-28
猜你喜欢
  • 2021-08-11
  • 2021-10-11
  • 2021-08-17
  • 2021-08-15
  • 2022-01-15
  • 2021-08-03
相关资源
相似解决方案