python:好用的 with 语法
手动清理资源占用是个很痛苦的事情,比如刚学编程时候,老鸟就建议:写完open xxx 之后一定要写一个配对儿的 close,然后再往他俩中间写逻辑。 python 现在有个好玩的东西,利用上下文可以自动释放掉一个对象: class test(): def __init__(self,msg): print(msg) def __enter__(self): print('Enter Object test') def __exit__(self, exc_type, exc_val, exc_tb): print('Exit Object test') object=test('Hello') print('***head of code block***') with object as t: print('Did something here...') print('***end of code block***') 运行结果如下: Hello ***head of code block*** Enter Object test Did something here... Exit...