0
点赞
收藏
分享

微信扫一扫

python with上下文的浅谈

python中的with一般用于上下文管理,什么是上下文管理,其实平时我们经常会用到,比如连接数据库 查询数据,操作完成后关闭连接。

还比如打开文件写入数据等操作。

具体实例:

class Myresource(object):

def __enter__(self):
print("processing")
return self

def __exit__(self, exc_type, exc_val, exc_tb):
if exc_tb:
print exc_val
print("process exception")
else:
print("no process exception")
return True

def query(self):
print ("query data")

with Myresource() as resource:

  resource.query()

 查看执行情况

processing
query data
no process exception

如果发生异常,比如:

with Myresource() as resource:

  1/0

查看执行情况:

processing
integer division or modulo by zero
process exception

 

__exit__ 最后的return非常的重要,如果不写或者写作return False
那么错误会在内部、外部抛出,这样可以继续在with增加try Expection来抓取错误信息,
如果是return True那么只会在内部抛出
integer division or modulo by zero

 



举报

相关推荐

0 条评论