【问题标题】:Does with always run __exit__总是运行 __exit__
【发布时间】:2020-04-25 19:09:49
【问题描述】:

我想知道 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 时它也会执行吗?

【问题讨论】:

    标签: python exit with-statement


    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 2019-06-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多