如何在Python函数执行前后增加额外的行为

yipeiwu_com6年前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)

运行如下:

In [4]: run()
运行花费时间:2.383398s。
Out[4]: 5000000

(喜欢刨根问底的可以去掉注释,并思考预计会有什么样的输出)。

今天无意间看到了Python的上下文管理器(Context Manager),发现也非常不错,其实这跟with语句是息息相关的,竟然以前一直未在意。

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()

总结

初略看了一点官方文档,上下文管理还是有点多内容的。Python发展到现在,其实不简单了。说简单,只是你自己不够与时俱进,掌握的都是老式三板斧而已。所以,知识需要不断更新,才能弥补自己的盲点,以上就是本文的全部内容,希望能大家的学习或者工作带来一定的帮助。

相关文章

python写程序统计词频的方法

python写程序统计词频的方法

在李笑来所著《时间当作朋友》中有这么一段: 可问题在于,当年我在少年宫学习计算机程序语言的时候,怎么可能想象得到,在20多年后的某一天,我需要先用软件调取语料库中的数据,然后用统计方法为...

Python读写文件基础知识点

Python读写文件基础知识点

在 Python 中,读写文件有 3 个步骤:  1.调用 open()函数,返回一个 File 对象。  2.调用 File 对象的 read()或 write()...

Python语法分析之字符串格式化

前序 There should be one - and preferably only one - obvious way to do it. ———— the Zen of Pyt...

python数据结构之图的实现方法

本文实例讲述了python数据结构之图的实现方法。分享给大家供大家参考。具体如下: 下面简要的介绍下: 比如有这么一张图:     A -> B &n...

Python回调函数用法实例详解

本文实例讲述了Python回调函数用法。分享给大家供大家参考。具体分析如下: 一、百度百科上对回调函数的解释: 回调函数就是一个通过函数指针调用的函数。如果你把函数的指针(地址)作为参数...