一個(gè)上下文管理器的類,最起碼要定義__enter__
和__exit__
方法。
讓我們來構(gòu)造我們自己的開啟文件的上下文管理器,并學(xué)習(xí)下基礎(chǔ)知識(shí)。
class File(object):
def __init__(self, file_name, method):
self.file_obj = open(file_name, method)
def __enter__(self):
return self.file_obj
def __exit__(self, type, value, traceback):
self.file_obj.close()
通過定義__enter__
和__exit__
方法,我們可以在with
語(yǔ)句里使用它。我們來試試:
with File('demo.txt', 'w') as opened_file:
opened_file.write('Hola!')
我們的__exit__
函數(shù)接受三個(gè)參數(shù)。這些參數(shù)對(duì)于每個(gè)上下文管理器類中的__exit__
方法都是必須的。我們來談?wù)勗诘讓佣及l(fā)生了什么。
with
語(yǔ)句先暫存了File
類的__exit__
方法File
類的__enter__
方法__enter__
方法打開文件并返回給with
語(yǔ)句opened_file
參數(shù).write()
來寫文件with
語(yǔ)句調(diào)用之前暫存的__exit__
方法__exit__
方法關(guān)閉了文件