python with语句的用法
<div id="cnblogs_post_body"> 今天在看Mentor要求的代码中碰到了with这一个关键词,不是太理解,便去google了一下,仔细看了一下别人的解释,基本对with有了一个初步的理解。with是python2.5以后才有的,它实质是一个控制流语句,with可以用来简化try-finally语句。它的主要用法是实现一个类__enter__()和__exit__()方法,基本形式如下:
<div class="cnblogs_code">class controlled_execution: def _enter__(self): set things up return thing def __exit__(self, type, value,traceback): tear thing downwith controlled_execution() as thing: some code
页:
[1]