国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

python實現Decorator模式實例代碼

2020-01-04 15:53:31
字體:
來源:轉載
供稿:網友

本文研究的主要是python/268598.html">python/301648.html">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_timedef 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就是一個裝飾器,其作用也很簡單,打印被裝飾函數運行時間。

裝飾器的語法如下:

@decdef func():pass

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

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

實例代碼

#-*-coding:utf-8-*-'''意圖:動態地給一個對象添加一些額外的職責。比通過生成子類更為靈活'''from abc import ABCMetaclass 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):    passclass 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模式實例代碼的全部內容,希望對大家有所幫助。感興趣的朋友可以繼續參閱本站其他相關專題,如有不足之處,歡迎留言指出。感謝朋友們對本站的支持!


注:相關教程知識閱讀請移步到python教程頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 长武县| 保定市| 张家界市| 青铜峡市| 蒙城县| 晋城| 泾阳县| 靖宇县| 娱乐| 通道| 绥德县| 休宁县| 海原县| 天津市| 当涂县| 平顶山市| 宣威市| 富川| 保靖县| 龙岩市| 额尔古纳市| 济南市| 临安市| 和林格尔县| 临沂市| 光泽县| 丹棱县| 镇赉县| 卓尼县| 德保县| 怀来县| 彭山县| 舞钢市| 吴旗县| 于都县| 孟连| 莱西市| 巨野县| 隆安县| 景洪市| 金堂县|