给Python函数执行前后添加额外行为

Susanna3407 7年前
   <p style="text-align:center"><img src="https://simg.open-open.com/show/c3d0718b7d55202db422d2988f2a440f.jpg"></p>    <p>以前想在函数前后添点啥额外功能(比如过滤、计时等)时,总是首先想到装饰器。比如这个计量所花费时间的程序:</p>    <pre>  <code class="language-python">from functools import wraps, partial  from time import time    def 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      @timing  def run():      l = []      for i in range(5000000):          l.extend([i])      return len(l)</code></pre>    <p>运行如下:</p>    <pre>  <code class="language-python">In [4]: run()  运行花费时间:2.383398s。  Out[4]: 5000000</code></pre>    <p>(喜欢刨根问底的可以去掉注释,并思考预计会有什么样的输出)。</p>    <p>今天无意间看到了Python的 <strong>上下文管理器(Context Manager)</strong> ,发现也非常不错,其实这跟 with 语句是息息相关的,竟然以前一直未在意。</p>    <pre>  <code class="language-python">from time import time    def 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()</code></pre>    <p>初略看了一点官方文档,上下文管理还是有点都内容的。Python发展到现在,其实不简单了。说简单,只是你自己不够与时俱进,掌握的都是老式三板斧而已。 所以,知识需要不断更新,才能弥补自己的盲点,这是我最想说的。</p>    <p> </p>    <p> </p>    <p>来自:http://www.2gua.info/post/63</p>    <p> </p>