python实现Decorator模式实例代码

yipeiwu_com5年前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模式实例代码的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!

相关文章

Django 自定义分页器的实现代码

Django 自定义分页器的实现代码

为什么要实现分页? 在大部分网站中分页的功能都是必要的,尤其是在后台管理中分页更是不可或缺 分页能带给用户更好的体验,也能减轻服务器的压力 对于分页来说,有许多方法都可以实现 例如把数据...

Python批量修改文本文件内容的方法

Python批量替换文件内容,支持嵌套文件夹 import os path="./" for root,dirs,files in os.walk(path): for name...

如何使用Python实现自动化水军评论

如何使用Python实现自动化水军评论

前言 玩博客一个多月了,渐渐发现了一些有意思的事,经常会有人用同样的评论到处刷,不知道是为了加没什么用的积分,还是纯粹为了表达楼主好人。那么问题来了,这种无聊的事情当然最好能够自动化咯,...

浅析Python 3 字符串中的 STR 和 Bytes 有什么区别

浅析Python 3 字符串中的 STR 和 Bytes 有什么区别

Python2的字符串有两种:str和Unicode,Python3的字符串也有两种:str和Bytes。Python2的str相当于Python3的Bytes,而Unicode相当于P...

Python+threading模块对单个接口进行并发测试

Python+threading模块对单个接口进行并发测试

本文实例为大家分享了Python threading模块对单个接口进行并发测试的具体代码,供大家参考,具体内容如下 本文知识点 通过在threading.Thread继承类中重写run(...