上下文管理器Context Manager实现原理

python中用with关键字可以创建一个上下文管理器,其为我们带来了很多便利,比如常见的文件的打开关闭操作等,是否觉得它用起来很酷?想不想定义自己的上下文管理器?现在就让我们一起来瞧瞧它的底层实现。

其实要定义自己的上下文管理器也很简单,只需要实现两个方法:
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__()方法,可见我们的目的已经达到!

猜你喜欢

转载自aisxyz.iteye.com/blog/2299175
今日推荐