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

                企業??AI智能體構建引擎,智能編排和調試,一鍵部署,支持知識庫和私有化部署方案 廣告
                # 對象變動 Mutation # 對象變動(Mutation) Python中可變(**mutable**)與不可變(**immutable**)的數據類型讓新手很是頭痛。簡單的說,可變(mutable)意味著"可以被改動",而不可變(immutable)的意思是“常量(constant)”。想把腦筋轉動起來嗎?考慮下這個例子: ~~~ foo = ['hi'] print(foo) # Output: ['hi'] bar = foo bar += ['bye'] print(foo) # Output: ['hi', 'bye'] ~~~ 剛剛發生了什么?我們預期的不是那樣!我們期望看到是這樣的: ~~~ foo = ['hi'] print(foo) # Output: ['hi'] bar = foo bar += ['bye'] print(foo) # Output: ['hi'] print(bar) # Output: ['hi', 'bye'] ~~~ 這不是一個bug。這是對象可變性(**mutability**)在作怪。每當你將一個變量賦值為另一個可變類型的變量時,對這個數據的任意改動會同時反映到這兩個變量上去。新變量只不過是老變量的一個別名而已。這個情況只是針對可變數據類型。下面的函數和可變數據類型讓你一下就明白了: ~~~ def add_to(num, target=[]): target.append(num) return target add_to(1) # Output: [1] add_to(2) # Output: [1, 2] add_to(3) # Output: [1, 2, 3] ~~~ 你可能預期它表現的不是這樣子。你可能希望,當你調用`add_to`時,有一個新的列表被創建,就像這樣: ~~~ def add_to(num, target=[]): target.append(num) return target add_to(1) # Output: [1] add_to(2) # Output: [2] add_to(3) # Output: [3] ~~~ 啊哈!這次又沒有達到預期,是列表的可變性在作怪。在Python中當函數被定義時,默認參數只會運算一次,而不是每次被調用時都會重新運算。你應該永遠不要定義可變類型的默認參數,除非你知道你正在做什么。你應該像這樣做: ~~~ def add_to(element, target=None): if target is None: target = [] target.append(element) return target ~~~ 現在每當你在調用這個函數不傳入`target`參數的時候,一個新的列表會被創建。舉個例子: ~~~ add_to(42) # Output: [42] add_to(42) # Output: [42] add_to(42) # Output: [42] ~~~
                  <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>

                              哎呀哎呀视频在线观看