Python天天美味(34) - Decorators详解

简介:

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 ():
    …

最终等价于:

=  A(f)

如果更复杂一些:

@A
@B
@C
def  f ():
    …

则相对于:

=  A(B(C(f)))

再看看有参数的例子,

@A(args)
def  f ():
    …

这时,f相当于:

_deco  =  A(args)
=  _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详解

 

 

本文转自CoderZh博客园博客,原文链接:http://www.cnblogs.com/coderzh/archive/2010/04/27/python-cookbook33-Decorators.html,如需转载请自行联系原作者

相关文章
|
2月前
|
测试技术 开发者 Python
Python中的装饰器(Decorators)原理与应用解析
在Python编程中,装饰器(Decorators)是一种强大的工具,能够灵活地扩展函数或类的功能,提高代码的可复用性和可维护性。本文将深入探讨装饰器的原理、使用方法以及常见应用场景,帮助读者更好地理解和运用这一重要的Python特性。
|
Python
关于python装饰器(Decorators)最底层理解的一句话
一个decorator只是一个带有一个函数作为参数并返回一个替换函数的闭包。 http://www.xxx.com/html/2016/pythonhexinbiancheng_0718/1044.html 一步步教你理解Python装饰器 我作完了全部的测试。
985 0
|
8天前
|
安全 Java 数据处理
Python网络编程基础(Socket编程)多线程/多进程服务器编程
【4月更文挑战第11天】在网络编程中,随着客户端数量的增加,服务器的处理能力成为了一个重要的考量因素。为了处理多个客户端的并发请求,我们通常需要采用多线程或多进程的方式。在本章中,我们将探讨多线程/多进程服务器编程的概念,并通过一个多线程服务器的示例来演示其实现。
|
8天前
|
程序员 开发者 Python
Python网络编程基础(Socket编程) 错误处理和异常处理的最佳实践
【4月更文挑战第11天】在网络编程中,错误处理和异常管理不仅是为了程序的健壮性,也是为了提供清晰的用户反馈以及优雅的故障恢复。在前面的章节中,我们讨论了如何使用`try-except`语句来处理网络错误。现在,我们将深入探讨错误处理和异常处理的最佳实践。
|
12天前
|
缓存 监控 Python
解密Python中的装饰器:优雅而强大的编程利器
Python中的装饰器是一种强大而又优雅的编程工具,它能够在不改变原有代码结构的情况下,为函数或类添加新的功能和行为。本文将深入解析Python装饰器的原理、用法和实际应用,帮助读者更好地理解和利用这一技术,提升代码的可维护性和可扩展性。
|
29天前
|
编译器 测试技术 C++
【Python 基础教程 01 全面介绍】 Python编程基础全攻略:一文掌握Python语法精髓,从C/C++ 角度学习Python的差异
【Python 基础教程 01 全面介绍】 Python编程基础全攻略:一文掌握Python语法精髓,从C/C++ 角度学习Python的差异
159 0
|
1天前
|
安全 数据处理 开发者
《Python 简易速速上手小册》第7章:高级 Python 编程(2024 最新版)
《Python 简易速速上手小册》第7章:高级 Python 编程(2024 最新版)
12 1
|
1天前
|
人工智能 数据挖掘 程序员
《Python 简易速速上手小册》第1章:Python 编程入门(2024 最新版)
《Python 简易速速上手小册》第1章:Python 编程入门(2024 最新版)
23 0
|
2天前
|
API Python
Python模块化编程:面试题深度解析
【4月更文挑战第14天】了解Python模块化编程对于构建大型项目至关重要,它涉及代码组织、复用和维护。本文深入探讨了模块、包、导入机制、命名空间和作用域等基础概念,并列举了面试中常见的模块导入混乱、不适当星号导入等问题,强调了避免循环依赖、合理使用`__init__.py`以及理解模块作用域的重要性。掌握这些知识将有助于在面试中自信应对模块化编程的相关挑战。
17 0
|
2天前
|
Python
Python金融应用编程:衍生品定价和套期保值的随机过程
Python金融应用编程:衍生品定价和套期保值的随机过程