<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>

                ??一站式輕松地調用各大LLM模型接口,支持GPT4、智譜、豆包、星火、月之暗面及文生圖、文生視頻 廣告
                # 基于類的實現 # 基于類的實現 一個上下文管理器的類,最起碼要定義`__enter__`和`__exit__`方法。 讓我們來構造我們自己的文件開啟的上下文管理器,并學習下基礎知識。 ~~~ class File(object): def __init__(self, file_name, method): self.file_obj = open(file_name, method) def __enter__(self): return self.file_obj def __exit__(self, type, value, traceback): self.file_obj.close() ~~~ 通過定義`__enter__`和`__exit__`方法,我們可以在`with`語句里使用它。我們來試試: ~~~ with File('demo.txt', 'w') as opened_file: opened_file.write('Hola!') ~~~ 我們的`__exit__`函數接受三個參數。這些參數對于每個上下文管理器類中的`__exit__`方法都是必須的。我們來談談在底層都發生了什么。 1. `with`語句先暫存了`File`類的`__exit__`方法 1. 然后它調用`File`類的`__enter__`方法 1. `__enter__`方法打開文件并返回給`with`語句 1. 打開的文件句柄被傳遞給`opened_file`參數 1. 我們使用`.write()`來寫文件 1. `with`語句調用之前暫存的`__exit__`方法 1. `__exit__`方法關閉了文件
                  <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>

                              哎呀哎呀视频在线观看