python的with和__enter__ 、 __exit__
__enter__(): 在使用with语句时调用,会话管理器在代码块开始前调用,返回值与as后的参数绑定
__exit__(): 会话管理器在代码块执行完成好后调用,在with语句完成时,对象销毁之前调用
test.txt的内容为hello world!
class Test(object): def __init__(self,name,flag): self.filename = name self.flag = flag def __enter__(self): ''' @summary: 使用with语句是调用,会话管理器在代码块开始前调用,返回值与as后的参数绑定 ''' print "__enter__:Open %s"%self.filename self.f = open(self.filename,self.flag) return self.f def __exit__(self,Type, value, traceback): ''' @summary: 会话管理器在代码块执行完成好后调用(不同于__del__)(必须是4个参数) ''' print "__exit__:Close %s"%self.filename self.f.close() def __del__(self): print "__del__" if __name__ == "__main__": with Test('test.txt','r+') as f: content = f.read() print content print "end"
来源:https://blog.csdn.net/xhw88398569/article/details/48691487
https://www.cnblogs.com/lipijin/p/4460487.html