文章来源:文章来源:
python with方法:
python推荐款使用with方法来读取文件,防止程序员打开文件后忘记关闭文件。
这是怎么实现的呢?
with可操纵的对象必须有__enter__
和__exit__
两个方法。
- with后面的对象在求值后,对象的
__enter__()
方法被调用。这将把with后面紧紧跟着的对像赋值给as后面的变量。 - with下面的语句执行好以后,将调用前面返回对象的
__exit__()
方法。
下面例子可以具体说明with如何工作:
class Sample:
def __enter__(self):
print("In __enter__()")
return "Foo"
def __exit__(self,type, value, trace):
print("In __exit__()")
def get_sample():
return Sample()
with get_sample() as sample:
print("sample:" + sample)
在 上面的 exit中得参数利可以定义with执行发生异常的时候应该如何处置。比如清理资源,关闭文件。