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 上面是经典的装饰者模式的实现,Python中通过Decorators可以实现成这样:
def milk_decorator(get_cost):
def get_milk_cost(self):
return get_cost(self) + 0.5
return get_milk_cost
class Coffee(object):
@milk_decorator
def get_cost(self):
return 1.0
coffee = Coffee()
print coffee.get_cost() #1.5 假设一下,如果有更多的,比如:Whip, Sprinkles, Tee, 必须为每个装饰者都实现一个函数,将会出现函数爆炸,我们可以只实现一个通用的Decorator函数,通过在get_cost函数添加多个@Decorator,这很符合Decorator Pattern的思想。
def get_cost_decorator(additional_cost):
def wrapper1(func):
def wrapper2(instance):
return func(instance) + additional_cost
return wrapper2
return wrapper1
class Coffee(object):
@get_cost_decorator(0.5)
@get_cost_decorator(0.7)
@get_cost_decorator(0.2)
def get_cost(self):
return 1.0
coffee = Coffee()
print coffee.get_cost() #2.4 上面的get_cost_decorator类看上去比较复杂,不要紧,一会再回头看这个函数。
Decorators基础
闲话不多说,先看下面的简单例子:
def myDecorator(func):
def newFunction():
print "inside newFunction"
func()
return newFunction
@myDecorator
def aFunction():
print "inside aFunction()"
aFunction() 最终输出:
inside newFunction
inside aFunction() 我们看到,myDecorator函数的参数其实是aFunction的函数地址,并且返回一个函数地址,返回的函数才是最终真正调用的地址。最终的调用,等价于:
aFunction = myDecorator(aFunction)
aFunction() 其中,myDecorator也可以使用class来实现,比如:
class myDecorator(object):
def __init__(self, func):
self.func = func
def __call__(self):
print "inside myDecorator"
self.func()
@myDecorator
def aFunction():
print "inside aFunction()" 最终,
aFunction() 相对于
aFunction = myDecorator(aFunction)
aFunction() # __call__
Decorators调用规律
上面的例子,我们可以很容易的得到这样一个规律:
@A
def f ():
… 最终等价于:
f = A(f) 如果更复杂一些:
@A
@B
@C
def f ():
… 则相对于:
f = A(B(C(f))) 再看看有参数的例子,
@A(args)
def f ():
… 这时,f相当于:
_deco = A(args)
f = _deco(f) 因此,A的实现也会相对复杂一些:
def A(args):
def wrapper1(f):
def wrapper2():
print “before call f()”
f()
return wrapper2
return wrapper1 有点绕吧,嗯,还算简单,我们回头看最开头那个例子,
@get_cost_decorator(0.5)
@get_cost_decorator(0.7)
@get_cost_decorator(0.2)
def get_cost(self):
return 1.0 相当于:
get_cost = get_cost_decorator(0.5)(get_cost_decorator(0.7)(get_cost_decorator(0.2)(get_cost))) # 绕晕了~~
Decorators典型应用 – singleton class
def singleton(cls):
instances = {}
def getinstance():
if cls not in instances:
instances[cls] = cls()
return instances[cls]
return getinstance
@singleton
class MyClass:
...
参考文章:
Decorators for Functions and Methods
Introduction to Python Decorators
Decorator pattern
[Python学习]decorator的使用 - limodou
Python 天天美味系列(总)
Python 天天美味(30) - python数据结构与算法之快速排序 Python 天天美味(31) - python数据结构与算法之插入排序
Python 天天美味(32) - python数据结构与算法之堆排序
Python 天天美味(33) - 五分钟理解元类(Metaclasses)[转]
Python 天天美味(34) - Decorators详解
运维网声明
1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网 享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com