最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

python實(shí)現(xiàn)Decorator模式實(shí)例代碼

 更新時(shí)間:2018年02月09日 15:43:02   作者:JasonLi-九黎  
這篇文章主要介紹了python實(shí)現(xiàn)Decorator模式實(shí)例代碼,簡(jiǎn)單介紹了裝飾器的含義和語(yǔ)法,分享了相關(guān)實(shí)例,小編覺(jué)得還是挺不錯(cuò)的,具有一定借鑒價(jià)值,需要的朋友可以參考下

本文研究的主要是python實(shí)現(xiàn)Decorator模式,具體介紹如下。

一般來(lái)說(shuō),裝飾器是一個(gè)函數(shù),接受一個(gè)函數(shù)(或者類)作為參數(shù),返回值也是也是一個(gè)函數(shù)(或者類)。首先來(lái)看一個(gè)簡(jiǎn)單的例子:

# -*- 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

代碼中,函數(shù)log_cost_time就是一個(gè)裝飾器,其作用也很簡(jiǎn)單,打印被裝飾函數(shù)運(yùn)行時(shí)間。

裝飾器的語(yǔ)法如下:

@dec

def func():pass

本質(zhì)上等同于: func = dec(func) 。

在上面的代碼(code snippet 0)中,把line12注釋掉,然后把line18的注釋去掉,是一樣的效果。另外staticmethod和classmethod是兩個(gè)我們經(jīng)常在代碼中用到的裝飾器,如果對(duì)pyc反編譯,得到的代碼一般也都是 func = staticmthod(func)這種模式。當(dāng)然,@符號(hào)的形式更受歡迎些,至少可以少拼寫一次函數(shù)名。

實(shí)例代碼

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


'''
意圖:動(dòng)態(tài)地給一個(gè)對(duì)象添加一些額外的職責(zé)。比通過(guò)生成子類更為靈活
'''
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()

結(jié)果

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

總結(jié)

以上就是本文關(guān)于python實(shí)現(xiàn)Decorator模式實(shí)例代碼的全部?jī)?nèi)容,希望對(duì)大家有所幫助。感興趣的朋友可以繼續(xù)參閱本站其他相關(guān)專題,如有不足之處,歡迎留言指出。感謝朋友們對(duì)本站的支持!

相關(guān)文章

最新評(píng)論

江口县| 固安县| 宁陕县| 修水县| 高平市| 潢川县| 平泉县| 新蔡县| 横峰县| 江城| 英德市| 潍坊市| 旬邑县| 砚山县| 开远市| 深圳市| 渝中区| 专栏| 天水市| 灯塔市| 海盐县| 荣成市| 冀州市| 大城县| 福海县| 太保市| 福泉市| 溧阳市| 天峻县| 汝城县| 乌拉特前旗| 江油市| 沂源县| 望都县| 利辛县| 繁昌县| 界首市| 儋州市| 深州市| 丹寨县| 关岭|