这些方法几乎是使对象与
with语句一起工作所需的全部。
在
__enter__打开并设置文件对象后,必须返回它。
在
__exit__你必须关闭文件对象。写入代码将在
with语句主体中。
class Meter(): def __init__(self, dev): self.dev = dev def __enter__(self): #ttysetattr etc goes here before opening and returning the file object self.fd = open(self.dev, MODE) return self.fd def __exit__(self, type, value, traceback): #Exception handling here close(self.fd)meter = Meter('dev/tty0')with meter as m: #here you work with the file object. m.read()


