python上下文管理器

python通过with实现对上下文管理器的调用

一、通过类实现的上下文管理

  类中要有__enter__()和__exit__()两个魔术方法

class Myopen(object):

  def __init__(self, file, mode):
    self.file = open(file, mode)

  def __enter__(self):
    return self.file

  def __exit__(self, type, value, Traceback):
    self.file.close()
    return True

with Myopen("text.txt", "w") as f:
  fi.write("测试上下文管理器")

二、使用函数实现上下文管理

  函数的实现需要使用 contextlib 模块,使用yeild 记录状态

from contextlib import contextmanager

@contextmanager
def myOpen(file, mode):
      f = open(file, mode)
      yield f
      f.close()


with myOpen("text.txt", "w") as f:
    f.write("context测试上下文管理器")
原文地址:https://www.cnblogs.com/chenzhiming/p/11101467.html