Python常量池

來源:互聯網
上載者:User

標籤:pytho   記憶體   機制   特點   對象   最佳化   相同   代碼塊   nbsp   

在python裡,有一個神奇的機制:常量池

Python 內部做了一些最佳化,Python把常用的整數對象都預先緩衝起來

特點:

  1.整數範圍: -5 -- 257

  2.它永遠不會被GC機制回收, 只要定義的整數變數在 範圍: -5  --  256內,會被全域解譯器重複使用, 257除外

  3.只要在這個 -5  --  256 範圍內,建立同一地區代碼塊的變數的值如果是相等的,那麼不會建立新對象(python萬物皆對象,數值也是對象),直接引用。

一:

a = 123b = 123print(id(a)) >>> 1744793632print(id(b)) >>> 1744793632 

二:

def test_a():    a = 123    print(id(a))def test_b():    b = 123    print(id(b))test_a()  >>> 1744793632
test_b() >>> 1744793632

三:奇葩的257


def test_a():
a = 257
b = 257
print(id(a)) # 1872078405424
print(id(b)) # 1872078405424


num1 = 257
num2 = 257
print(id(num1)) # 1872077827792
print(id(num2)) # 1872077827792
test_a()

257 這個整數對象是區分範圍的,它只有在相同的範圍, 記憶體位址才會相同

 

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.