尝试使用语句和上下文管理器理解 python [英] Trying to understand python with statement and context managers

查看:55
本文介绍了尝试使用语句和上下文管理器理解 python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对此很陌生,只是想了解 with 语句.我知道它应该替换 try/except 块.

I am new to this, and am just trying to understand the with statement. I understand that it is supposed to replace the try/except block.

现在假设我做这样的事情:

Now suppose I do something like this:

try:
   name='rubicon'/2 # to raise an exception
except Exception as e:
   print "no not possible"
finally:
   print "Ok I caught you"

如何用上下文管理器替换它?

How do I replace this with a context manager?

推荐答案

with 并没有真正取代 try/except,但是,相反,try/finally.尽管如此,您可以让上下文管理器在异常情况下做一些与非异常情况不同的事情:

with doesn't really replace try/except, but, rather, try/finally. Still, you can make a context manager do something different in exception cases from non-exception ones:

class Mgr(object):
    def __enter__(self): pass
    def __exit__(self, ext, exv, trb):
        if ext is not None: print "no not possible"
        print "OK I caught you"
        return True

with Mgr():
    name='rubicon'/2 #to raise an exception

return True 部分是上下文管理器决定抑制异常的地方(就像您通过不在 except 子句中重新引发它一样).

The return True part is where the context manager decides to suppress the exception (as you do by not re-raising it in your except clause).

这篇关于尝试使用语句和上下文管理器理解 python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆