总是 运行 __exit__

Does with always run __exit__

我想知道 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() 代替 pass 也会执行吗?

__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