我们还没有谈到__exit__方法的这三个参数:type, value和traceback。 在第4步和第6步之间,如果发生异常,Python会将异常的type,value和traceback传递给__exit__方法。 它让__exit__方法来决定如何关闭文件以及是否需要其他步骤。在我们的案例中,我们并没有注意它们。
__exit__
type
value
traceback
那如果我们的文件对象抛出一个异常呢?万一我们尝试访问文件对象的一个不支持的方法。举个例子:
with File('demo.txt', 'w') as opened_file: opened_file.undefined_function('Hola!')
我们来列一下,当异常发生时,with语句会采取哪些步骤。
with
在我们的案例中,__exit__方法返回的是None(如果没有return语句那么方法会返回None)。因此,with语句抛出了那个异常。
None
return
Traceback (most recent call last): File "<stdin>", line 2, in <module> AttributeError: 'file' object has no attribute 'undefined_function'
我们尝试下在__exit__方法中处理异常:
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): print("Exception has been handled") self.file_obj.close() return True with File('demo.txt', 'w') as opened_file: opened_file.undefined_function() # Output: Exception has been handled
我们的__exit__方法返回了True,因此没有异常会被with语句抛出。
True
这还不是实现上下文管理器的唯一方式。还有一种方式,我们会在下一节中一起看看。
Copyright© 2013-2020
All Rights Reserved 京ICP备2023019179号-8