Python-是否始终运行__exit __

问题描述 投票:0回答:1

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

python exit with-statement
1个回答
1
投票

是,当调用__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
© www.soinside.com 2019 - 2024. All rights reserved.