python学习笔记27:with语句工作原理

1. 说明

  1. with语句是从python2.5加入的与异常处理相关的功能。
  2. with语句适用于对资源进行访问的场合,确保不管使用过程中是否发生异常都会执行必要的“清理”操作,释放资源,比如文件使用后自动关闭、线程中锁的自动获取和释放等。
  3. with语句需要有上下文管理器才能工作。
  4. 文件操作的open语句已经支持with。

2. 例

通过自定义一个my_open_read()函数,说明with的工作原理:

代码:

'''
定义一个函数,用来打开文件,
这个函数返回一个类实例: CMyFile(filename)作为上下文管理器
当这个函数出现在with语句中时,得到的是__enter__()函数的返回值
'''
def my_open_read(filename):
    return CMyFile(filename)

'''定义一个class 这个class就是上下文件管理器'''
class CMyFile(object):
    def __init__(self, filename):
        self.filename = filename

    '''__enter__函数, 返回文件handle, 交给with语句'''
    def __enter__(self):
        print(f'    __enter__ begin')
        self.f = open(self.filename, 'r')
        print(f'        self.f = open(self.filename, "r")')
        print(f'    __enter__ end')
        print(f'')
        return self.f

    '''__exit__函数, 在with块语句执行完后, 清理没有关闭的句柄'''
    def __exit__(self, exc_type, exc_val, exc_tb):
        print(f'    __exit__ begin, close file handle')
        self.f.close()
        print(f'        self.f.close()')
        print(f'    __exit__ end')
        print(f'')

'''
总结:
1. my_open_read() 返回CMyFile的一个实例
2. with my_open_read(), 得到CMyFile的__enter__()函数的返回值: 文件Handler
3. with my_open_read() as fid, 将文件handler命名为fid
4. 在with块语句中使用fid
5. 在with块语句结束时,调用CMyFile的__exit__()函数,关闭Handler.
'''
print('__with__ begin')
with my_open_read('file.txt') as fid:
    print('    with_block begin')
    print('        read file handle')
    print('    with_block end')
    print(f'')
print('__with__ end')

执行结果

E:myfilepython	est>python py_ex.py
__with__ begin
    __enter__ begin
        self.f = open(self.filename, "r")
    __enter__ end

    with_block begin
        read file handle
    with_block end

    __exit__ begin, close file handle
        self.f.close()
    __exit__ end

__with__ end
E:myfilepython	est>
原文地址:https://www.cnblogs.com/gaiqingfeng/p/13279884.html