with语句相当于你定义一个类的时候定义了__enter__()和__exit__()这个两个方法。在我们进行文件操作的的时候会用到open方法,后面有了with open以后就不再只使用open方法了,为什么?因为with open方法简单,我们不用再去管关闭文件了,即使中间发生异常,with open也会帮我们把文件关闭掉,以下示例演示下with open方法;class File(object):"""文件操作类"""def __init__(self, filepath, mode):self.filepath = filepathself.mode = modedef __enter__(self):"""打开文件"""self.file = open(self.filepath, self.mode)print("打开文件")return self.filedef __exit__(self, exc_type, exc_val, exc_tb):"""关闭文件"""print("关闭文件")self.file.close()if __name__ == '__main__':with File('log.log', 'r') as file:file.write("家啊")可以看出来有了__enter__()和__exit__(),我们自定义的类也可以使用with了