如题。简单看了下io.py部分的源码,只看到了open的定义是直接返回对象,没有看到是如何实现上下文管理器的。Google了半天也没有结果。求知乎大神解答!
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.
<code class="language-python"> <span class="c">### Context manager ###</span> <span class="k">def</span> <span class="nf">__enter__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="sd">"""Context management protocol. Returns self."""</span> <span class="bp">self</span><span class="o">.</span><span class="n">_checkClosed</span><span class="p">()</span> <span class="k">return</span> <span class="bp">self</span> <span class="k">def</span> <span class="nf">__exit__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">):</span> <span class="sd">"""Context management protocol. Calls close()"""</span> <span class="bp">self</span><span class="o">.</span><span class="n">close</span><span class="p">()</span> </code>