python实现Decorator模式实例代码

栏目: 编程语言 · Python · 发布时间: 6年前

内容简介:这篇文章主要介绍了python实现Decorator模式实例代码,简单介绍了装饰器的含义和语法,分享了相关实例,小编觉得还是挺不错的,具有一定借鉴价值,需要的朋友可以参考下

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

总结


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Algorithms

Algorithms

Sanjoy Dasgupta、Christos H. Papadimitriou、Umesh Vazirani / McGraw-Hill Education / 2006-10-16 / GBP 30.99

This text, extensively class-tested over a decade at UC Berkeley and UC San Diego, explains the fundamentals of algorithms in a story line that makes the material enjoyable and easy to digest. Emphasi......一起来看看 《Algorithms》 这本书的介绍吧!

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具