💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
with...as python 控制流语句,是简化版的try except finally。 with expression [as variable]: with-block with 语句实质是上下文管理。 1、上下文管理协议。包含方法__enter__() 和 __exit__(),支持该协议对象要实现这两个方法。 2、上下文管理器,定义执行with语句时要建立的运行时上下文,负责执行with语句块上下文中的进入与退出操作。 3、进入上下文的时候执行__enter__方法,如果设置as var语句,var变量接受__enter__()方法返回值。 4、如果运行时发生了异常,就退出上下文管理器。调用管理器__exit__方法。 应用场景 1、文件操作。 2、进程线程之间互斥对象。 3、支持上下文其他对象 1. 方式1 #?简单处理 file?=?open("1.txt") data?=?file.read() file.close() 2. 方式2 #?增加异常处理 try: ????f?=?open('1.txt') except: ????print?'fail?to?open' ????exit(-1) finally ????f.close() 3. 方式3 #?使用with with?open("/tmp/1.txt")?as?file: ????data?=?file.read() ???? 1.?方式1?对异常没处理 2.?方式2?写法冗长 3. with 简洁 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 with 可以处理异常 with as 表达式简化了finally工作,保持代码的优雅性。