【发布时间】:2021-04-16 10:57:55
【问题描述】:
这是一个示例代码:
class test :
def __init__(self, text) :
self.text = text
def __enter__(self) :
print("some text" + self.text)
def __exit__(self, *args) :
self.text = None
print(args)
return True
with test("hello world") :
pass
with test(12) :
pass
我在__enter__ 函数中使用字符串连接,这样如果文本参数是一个int,就会出现TypeError(但不应该因为with语句而抛出)
如果在分配给目标列表的过程中发生错误,它将被视为与套件中发生的错误相同。
如果套件因异常而退出,并且 exit() 方法的返回值为 false,则重新引发异常。如果返回值为真,则抑制异常,并继续执行 with 语句之后的语句。
所以这里 __exit__ 返回 True 那么为什么当我运行此示例代码时会抛出错误?
感谢您的帮助
【问题讨论】:
-
__exit__甚至没有到达,因为__enter__没有成功完成。
标签: python with-statement