
本文共 2814 字,大约阅读时间需要 9 分钟。
Python ������������������������������������������
������������������
������������������������ Context Manager
���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������
with ������
with
��������� Python ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������
with ������������������������
with open('test.txt', 'a') as f: f.write('���������������\n')
���������������������������������������������test.txt
���������������������������������������������������
���������������with
���������������������������������������������������f.close()
���
��� with
���������������������������������������������������������������as
������������������������������������ f ������f ���������������/���������������������������with
������������������������������������������������������������������������������������������"������"���������
���������������������������
with
��������������������������������������� __enter__
��� __exit__
���������������������������__enter__
���������������������������������������������������__exit__
���������������������������������������������������������
���������������������������
������������ __enter__
��� __exit__
������������������������������������������������������
class OpenFile(object): def __init__(self, file, mode): self._file = file self._mode = mode def __enter__(self): self._handle = open(self._file, self._mode) return self._handle def __exit__(self, exc_type, exc_val, exc_tb): self._handle.close()with OpenFile('test01.txt', 'w') as f: f.write('������������������������\n')
��������������������������� OpenFile
������������������������������������������������������������������������������������������
���������������������������������
__exit__
������������������������ exc_type
���exc_val
��� exc_tb
������������������������ with
��������������������������� __exit__
������ True
������������������������������������������������������������
class OpenFile(object): def __init__(self, file, mode): self._file = file self._mode = mode def __enter__(self): self._handle = open(self._file, self._mode) return self._handle def __exit__(self, exc_type, exc_val, exc_tb): self._handle.close() if exc_type == "None": print('������������') else: print(f'Exception: {exc_type}') return Truewith OpenFile('test01.txt', 'r') as f: f.write('������������������������\n')
������������ __exit__
������ True
������������������������������������������ exc_type
������������������������������
发表评论
最新留言
关于作者
