时间:2021-07-01 10:21:17 帮助过:63人阅读
open() returns a file object whose type depends on the mode, and
through which the standard file operations such as reading and writing
are performed. When open() is used to open a file in a text mode ('w',
'r', 'wt', 'rt', etc.), it returns a TextIOWrapper. When used to open
a file in a binary mode, the returned class varies: in read binary
mode, it returns a BufferedReader; in write binary and append binary
modes, it returns a BufferedWriter, and in read/write mode, it returns
a BufferedRandom.
### Context manager ###
def __enter__(self):
"""Context management protocol. Returns self."""
self._checkClosed()
return self
def __exit__(self, *args):
"""Context management protocol. Calls close()"""
self.close()
只要有__enter__和__exit__方法,就能用在with语句里,open返回的对象有这两个方法,就可以了,不必在open方法内做什么手脚。
Python 的上线文管理器使用with关键字,用来定义with后面这个缩进级别,进入和跳出的行为,是语法糖的一种。open是一个调用用于实例化file类的函数,而file类只不过是一个拥有__enter__和__exit__(这种前后都有两个下划线的在Python中叫做“魔法方法”,除了这两个还有很多,有兴趣可以去查一下)的类,用在with中时,程序会自动在进出这个程序块时调用这两个函数,如果没用with就要手动管理,自己调用close()。如果想要自己实现类似的功能,用回调就,或者单独封装成装饰器(装饰器其实也是Python的一种语法糖)都可以。
跟Java的Closeable一样 定义好释放资源的方式 通过语法糖隐藏部分重复代码
你google context manager就有结果了