使用上下文管理器是为了更方便处理变量的释放,避免有的时候忘记关闭一些东西,比如socket,file等
1 第一种是使用类的方法来实现,只要实现两个魔法方法就可以了
def __enter__(self):和def __exit__(self,*args):方法
class File:
def __init__(self,path,mode):
self.path=path
self.mode=mode
self.hd=None
def __enter__(self):
self.hd=open(self.path,self.mode)
return self.hd
def __exit__(self,*args):
if self.hd:
self.hd.close()
print('关闭了文件')
else:
print('没有相应文件')
def main():
with File('123.txt','a+') as f:
f.write('zzzzzzzzzzzzzzzzzzzzzzzzzzzzzz\n')
if __name__ == '__main__':
main()
2,使用生成器来实现及yiled方法和contextlib模块来实现
import contextlib
@contextlib.contextmanager
def my_file(path,mode):
"""利用模块和生成器来实现上下文管理器"""
f=open(path,mode)
yield f
f.close()
print('关闭了文件')
def main():
with my_file('123.txt','a+') as f:
f.write('1234567890\n')
if __name__ == '__main__':
main()