python实现Decorator模式实例代码

作者:JasonLi-九黎 时间:2022-05-10 06:04:56 

本文研究的主要是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...
>>>

来源:http://blog.csdn.net/jklfjsdj79hiofo/article/details/8679779

标签:python,decorator,模式
0
投稿

猜你喜欢

  • Overflow Auto && Position Relative

    2009-09-03 12:02:00
  • 防止网站被采集的理论分析以及十条方法对策第1/2页

    2011-03-29 10:38:00
  • 七十六个网站用户体验要点

    2010-08-11 14:52:00
  • Python 运行 shell 获取输出结果的实例

    2023-08-02 16:51:18
  • PHP生成静态页面详解

    2023-11-21 06:50:43
  • JS清空上传控件input(type="file")的值的代码第1/2页

    2023-08-13 07:22:28
  • 客户认同的就是好商品

    2009-08-31 16:41:00
  • 用好Frontpage中的各种回车

    2008-02-21 14:33:00
  • 在网页中显示可拖动月历

    2010-07-13 12:09:00
  • PL/SQL 类型格式转换

    2009-02-26 11:07:00
  • python+flask编写接口实例详解

    2022-10-09 16:09:41
  • response.setHeader()方法设置http文件头的值

    2010-03-11 22:43:00
  • 如何用Python徒手写线性回归

    2023-06-12 13:47:14
  • 自定义404错误页面实现自动跳转

    2007-12-10 18:25:00
  • asp显示左边的n个字符自动识别汉字的函数

    2007-09-13 12:16:00
  • Python3.5迭代器与生成器用法实例分析

    2022-11-03 14:50:47
  • php curl登陆qq后获取用户信息时证书错误

    2023-11-15 08:23:39
  • 简单理解PHP的面向对象编程方式

    2023-06-13 15:38:08
  • 全面理解javascript的caller,callee,call,apply概念

    2007-12-02 17:44:00
  • ASP开发10条经验总结

    2007-09-30 13:36:00
  • asp之家 网络编程 m.aspxhome.com