只需要在自定义类里实现__enter__和__exit__两个方法,即可以让类支持上下文管理,

__enter__ 执行前调用一些初始化工作

__exit__ 执行完毕后调用一些释放工作,像关闭句柄之类

class MyOpen(object):
    def __init__(self, pfile, mode='r', ignore_exception=False):
        self.pfile, self.mode = pfile, mode
        self.fd = None
        self.ignore_exception = ignore_exception

    def __enter__(self):
        fd = open(self.pfile, self.mode)
        self.fd = fd
        print 'open'
        return self

    def read(self):
        print 'call read'

    def __exit__(self, exc_type, exc_val, exc_tb):
        print u'清理工作'
        if self.fd:
            print 'close....'
            self.fd.close()
        return self.ignore_exception

以上代码实现一个简单的像open功能的类

值得注意的是__exit__的返回值,这个函数如果返回true,则这个类里出现的异常不会向上传递

myfile = 'c:\\a.py'
with MyOpen(myfile, ignore_exception=True) as fp:
    fp.read()
    raise Exception("ex4Test")