python实现Decorator模式实例代码

yipeiwu_com6年前Python基础

本文研究的主要是python实现Decorator模式,具体介绍如下。

一般来说,装饰器是一个函数,接受一个函数(或者类)作为参数,返回值也是也是一个函数(或者类)。首先来看一个简单的例子:

# -*- coding: utf-8 -*-
def log_cost_time(func):
  def wrapped(*args, **kwargs):
    import time
    begin = time.time()
    try:
      return func(*args, **kwargs)
    finally:
      print 'func %s cost %s' % (func.__name__, time.time() - begin)
  return wrapped
 
@log_cost_time
def complex_func(num):
  ret = 0
  for i in xrange(num):
    ret += i * i
  return ret
#complex_func = log_cost_time(complex_func)
 
if __name__ == '__main__':
  print complex_func(100000)
 
code snippet 0

代码中,函数log_cost_time就是一个装饰器,其作用也很简单,打印被装饰函数运行时间。

装饰器的语法如下:

@dec

def func():pass

本质上等同于: func = dec(func)

在上面的代码(code snippet 0)中,把line12注释掉,然后把line18的注释去掉,是一样的效果。另外staticmethod和classmethod是两个我们经常在代码中用到的装饰器,如果对pyc反编译,得到的代码一般也都是 func = staticmthod(func)这种模式。当然,@符号的形式更受欢迎些,至少可以少拼写一次函数名。

实例代码

#-*-coding:utf-8-*-


'''
意图:动态地给一个对象添加一些额外的职责。比通过生成子类更为灵活
'''
from abc import ABCMeta

class Component():
  __metaclass__ = ABCMeta
  def __init__(self):
    pass
  def operation(self):
    pass
  
class ConcreteComponent(Component):
  def operation(self):
    print 'ConcreteComponent operation...'

class Decorator(Component):
  def __init__(self, comp):
    self._comp = comp
  def operation(self):
    pass

class ConcreteDecorator(Decorator):
  def operation(self):
    self._comp.operation()
    self.addedBehavior()
  def addedBehavior(self):
    print 'ConcreteDecorator addedBehavior...' 
       
if __name__ == "__main__":
   comp = ConcreteComponent()
   dec = ConcreteDecorator(comp)
   dec.operation()

结果

======================= RESTART: C:/Python27/0209.2.py =======================
ConcreteComponent operation...
ConcreteDecorator addedBehavior...
>>>

总结

以上就是本文关于python实现Decorator模式实例代码的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!

相关文章

Python的条件表达式和lambda表达式实例

条件表达式 条件表达式也称为三元表达式,表达式的形式:x if C else y。流程是:如果C为真,那么执行x,否则执行y。 经过测试x,y,C可以是函数,表达式,常量等等; de...

Python找出9个连续的空闲端口

一、项目需求 安装某软件,配置时候需要填写空闲的端口。查看5个平台的某个端口是否被占用 5个平台为windows, linux, aix, hp, solaris 二、实现方案有两种 1...

Python自动抢红包教程详解

Python自动抢红包教程详解

0 引言 提到抢红包,就不得不提Xposed框架,它简直是个抢红包的神器,但使用Xposed框架有一个前提条件:手机需要root,对于苹果手机的话就需要越狱了。现在的手机想要root...

python Tkinter版学生管理系统

python Tkinter版学生管理系统

本文实例为大家分享了python Tkinter版学生管理的具体代码,供大家参考,具体内容如下 Tkinter是python自带的UI包,无需下载,只需要导入 tkinter 文档 //...

Django Rest framework解析器和渲染器详解

Django Rest framework解析器和渲染器详解

解析器 解析器的作用就是服务端接收客户端传过来的数据,把数据解析成自己想要的数据类型的过程. 本质就是对请求体中的数据进行解析. Content-type:用于声明我给你传的是什么类型...