我想知道with语句的__exit__
是否总是像finally
一样执行。使用此代码:
class WithTest(object):
def __enter__(self):
print("entering")
return self
def __exit__(self, a, b, c):
print("exiting")
with WithTest():
pass
即使调用exit()
代替通过,它也会执行吗?
是,当调用__exit__
时执行exit()
。调用os._exit
之类的内容时,它不会退出。此代码:
class WithTest(object):
def __enter__(self):
print("entering")
return self
def __exit__(self, a, b, c):
print("exiting")
with WithTest():
exit()
将打印:
entering
exiting