<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                合規國際互聯網加速 OSASE為企業客戶提供高速穩定SD-WAN國際加速解決方案。 廣告
                [TOC] # 使用with 一般文件處理是這樣 ~~~ def m2(): f = open('./output.txt', 'w') try: f.write('py') except IOError: print('error') finally: f.close() m2() ~~~ 用with 一種更加簡潔,優雅的方式就是with關鍵字 open方法的返回值賦值給變量f,當離開with代碼塊的時候,系統自動調用`f.close()`方法 with的作用和使用try/finally語句是一樣的 ~~~ def m2(): with open('./output.txt', 'w') as f: f.write('py') m2() ~~~ # 上下文管理器 任何實現了`__enter__()`和`__exit__()`方法的對象都可以稱為上下文管理器,上下文管理器對象可以使用with關鍵字.顯然文件file對象也實現了上下文管理器 我們模擬一個 ~~~ class File(object): def __init__(self, filename, mode): self.filename = filename self.mode = mode def __enter__(self): print('enter....') self.f = open(self.filename, self.mode) return self.f def __exit__(self, **args): print('will exit') self.f.close() ~~~ `__enter__()`方法返回資源對象,這里就是你要打開的那個對象文件 `__exit__()`方法處理一些清除工作 因為這個類實現了上下文管理器,我們可以使用with了 ~~~ with File('./output.txt', 'w') as f: print('writing') f.write('java') ~~~ # 另一種方式實現上下文管理 python還提供一個contextmanager的裝飾器,更進一步簡化了上下文管理器的實現方式.通過yield將函數分割成兩部分. yield之前的語句在`__enter__`方法執行,yield以后的語句在__exit__方法中執行. 緊跟在yield后面的是函數的返回值 ~~~ from contextlib import contextmanager @contextmanager def my_open(path, mode): f = open(path, mode) yield f f.close() ~~~ 調用 ~~~ with my_open('output.txt', 'w') as f: f.write('hello') ~~~
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看