python with as用法

时间:2023-03-09 18:34:48
python with as用法

with as用途:取代原来的try...finally,主要是用于处理异常

基本语法;with EXPRESSION [ as VARIABLE] WITH-BLOCK

基本要求:with所求值的对象必须有一个__enter__()方法,一个__exit__()方法。

紧跟with后面的语句被求值后,返回对象的__enter__()方法被调用,这个方法的返回值将被赋值给as后面的变量。

当with后面的代码块全部被执行完之后,将调用前面返回对象的__exit__()方法。

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