其实要定义自己的上下文管理器也很简单,只需要实现两个方法:
1、__enter__(self)
2、__exit__(self, exc_type, exc_value, traceback)
其中__enter__()方法会在创建时调用,可以把它返回的对象绑定到as指定的变量上,而__exit__()方法则会在退出上下文管理器时调用,它的三个参数描述了退出时发生的异常,没有发生的话就为None。
实现思路就是这样,下面举一例,用以模拟文件的操作过程(注:本人用的是python 3.5):
#创建过程: class FileSimulator: def __init__(self, filePath, mode='r'): self.filePath = filePath self.mode = mode def __enter__(self): print('--------opened %s---------\n' %self.filePath) return self def __exit__(self, exc_type, exc_value, traceback): print('\n--------%s closed-------' %self.filePath) def read(self): print('content content content...') def write(self, strToWrite): print('write-->%s' %strToWrite) #调用过程: with FileSimulator(r'/home/python/test.py') as fd: fd.read() fd.write('just try it!')
#输出结果: --------opened /home/python/test.py--------- content content content... write-->just try it! --------/home/python/test.py closed-------
为了简单一些,在此我没有定义打开模式,不过根据结果可看出,确实是先调用了__enter__()方法,最后退出时调用了__exit__()方法,可见我们的目的已经达到!