(python)對象的引用

來源:互聯網
上載者:User

標籤:bsp   log   列印   print   記憶體位址   int   開始   end   python   

對比下列兩個例子:

例子1:

a=10b=aa=a+2print "a=",a,"b=",b

結果:a= 12 b= 10 

a+2後,b仍然是10

例子2:

aa=[1,2,4]bb=aaaa.append(3)print "aa=",aa,"bb=",bb

  

結果:aa= [1, 2, 4, 3] bb= [1, 2, 4, 3]

aa增加一個元素3後,bb也增加了元素3

例子1和例子2為什麼會出現兩種不同情況呢?

我們再用id()函數列印出變數a、b、aa、bb的記憶體位址:

例子1:

 

a=10b=aprint id(a)print id(b)a=a+2 print "a=",a,"b=",bprint id(a)print id(b)

  

結果:

31815632
31815632
a= 12 b= 10
31815584
31815632

說明a、b兩個變數一開始指向的是同一個記憶體位址。而a=a+2後,a變數便不再是之前的那個a變數,而指向了另一個記憶體位址。但b變數還是之前的那個a變數。

 

例子2:

aa=[1,2,4]bb=aaprint id(aa)print id(bb)aa.append(3)print "aa=",aa,"bb=",bbprint id(aa)print id(bb)

結果:

38994120
38994120
aa= [1, 2, 4, 3] bb= [1, 2, 4, 3]
38994120
38994120

剛開始aa、bb指向的是同一個記憶體位址。aa.append(3)後,aa和bb仍然指向的是同一個記憶體位址,所以aa增加一個元素後,bb也跟著增加了一個元素


 

 

 

 

(python)對象的引用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.