with与上下文管理器

with主要为了解决资源释放问题,可以简化代码,下面是两种应用with的例子:

1、通过重写__enter__和__exit__方法实现:

 1 # coding:utf-8
 2 
 3 class File(object):
 4     def __init__(self, filename, mode):
 5         self.filename = filename
 6         self.mode = mode
 7         
 8     def __enter__(self):
 9         print("enter")
10         self.f = open(self.filename, self.mode)
11         return self.f
12         
13     def __exit__(self, *args):
14         print("exit")
15         self.f.close()
16         
17         
18 with File("out.txt", "w") as f:
19     f.write("Happy New Year!")

2、通过上下文管理器实现:

 1 # coding:utf-8
 2 
 3 from contextlib import contextmanager
 4 
 5 @contextmanager
 6 def my_open(path, mode):
 7     f = open(path, mode)
 8     yield f
 9     f.close()
10     
11 
12 with my_open("out1.txt", "w") as f:
13     f.write("hello eric")

 

posted on 2018-12-31 13:48  361度的天空  阅读(95)  评论(0)    收藏  举报

导航