温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

使用python实现Decorator模式的案例

发布时间:2021-03-23 11:46:58 来源:亿速云 阅读:153 作者:小新 栏目:开发技术

小编给大家分享一下使用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模式的案例”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI