with與上下文管理器
阿新 • • 發佈:2018-12-31
imp __init__ 解決 def text name urn 重寫 style
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")
with與上下文管理器