如何在Python函數執行前後增加額外的行為

來源:互聯網
上載者:User
首先來看一個小程式,這個是計量所花費時間的程式,以下是以往的解決樣本

from functools import wraps, partialfrom time import timedef timing(func=None, frequencies=1): if func is None:  # print("+None")  return partial(timing, frequencies=frequencies) # else:  # print("-None") @wraps(func) def _wrapper(*args, **kwargs):  start_time = time()  for t in range(frequencies):   result = func(*args, **kwargs)  end_time = time()  print('運行花費時間:{:.6f}s。'.format(end_time-start_time))  return result return _wrapper@timingdef run(): l = [] for i in range(5000000):  l.extend([i]) return len(l)

運行如下:

In [4]: run()運行花費時間:2.383398s。Out[4]: 5000000

(喜歡刨根問底的可以去掉注釋,並思考預計會有什麼樣的輸出)。

今天無意間看到了Python的上下文管理器(Context Manager),發現也非常不錯,其實這跟with語句是息息相關的,竟然以前一直未在意。

from time import timedef run2(): l = [] for i in range(5000000):  l.extend([i]) return len(l)class ElapsedTime(): def __enter__(self):  self.start_time = time()  return self def __exit__(self, exception_type, exception_value, traceback):  self.end_time = time()  print('運行花費時間:{:.6f}s。'.format(self.end_time - self.start_time))with ElapsedTime(): run2()

總結

初略看了一點官方文檔,上下文管理還是有點多內容的。Python發展到現在,其實不簡單了。說簡單,只是你自己不夠與時俱進,掌握的都是老式三板斧而已。所以,知識需要不斷更新,才能彌補自己的盲點,以上就是本文的全部內容,希望能大家的學習或者工作帶來一定的協助。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.