您好,登錄后才能下訂單哦!
小編給大家分享一下Python 字符串池化的前提,希望大家閱讀完這篇文章后大所收獲,下面讓我們一起去探討吧!
前言
在 Python 中經常通過內存池化技術來提高其性能,那么問題來了,在什么情況下會池化呢; 讓我們通過幾個例子進行一下理解一下.
預備知識
在查看例子之前,首先要提 python 中的一個函數 id(),讓我們看一下函數說明:
id(obj, /) Return the identity of an object. This is guaranteed to be unique among simultaneously existing objects. (CPython uses the object \'s memory address.)
通過上述說明,可以得知 id() 將會返回對像的唯一標識,在 CPython 中將會返回內存地址,也就是說如果兩個對象 的 id 值一樣,可以說著兩個對象是相同的了.
例子
example 00
a = "" b = "" print(id(a),id(b)) print(a is b)
輸出結果:
>>> a = ""
>>> b = ""
>>> print(id(a),id(b))
2114853370544 2114853370544
>>> print(a is b)
True
example 01
a = "a" b = "a" print(id(a),id(b)) print(a is b)
輸出結果:
>>> a = "a"
>>> b = "a"
>>> print(id(a),id(b))
2114883022608 2114883022608
>>> print(a is b)
True
example 02
a = "magic_string" b = "magic" + "_" + "string" print(id(a),id(b)) print(a is b)
輸出結果:
>>> a = "magic_string"
>>> b = "magic" + "_" + "string"
>>> print(id(a),id(b))
2114887161136 2114887161136
>>> print(a is b)
True
example 03
a = "magic!" b = "mgaic!" print(id(a),id(b)) print(a is b)
輸出結果:
>>> a = "magic!"
>>> b = "mgaic!"
>>> print(id(a),id(b))
2114885855416 2114889455408
>>> print(a is b)
False
example 04
a,b = "magic!","magic!" print(id(a),id(b)) print(a is b)
輸出結果:
>>> a,b = "magic!","magic!"
>>> print(id(a),id(b))
2114885691912 2114885691912
>>> print(a is b)
True
example 05
a = "!" b = "!" print(id(a),id(b)) print(a is b)
輸出結果:
>>> a = "!"
>>> b = "!"
>>> print(id(a),id(b))
140564571922024 140564571922024
>>> print(a is b)
True
example 06
print(a*20 is 'aaaaaaaaaaaaaaaaaaaa') print(a*21 is 'aaaaaaaaaaaaaaaaaaaaa')
輸出結果:
>>> print(a*20 is 'aaaaaaaaaaaaaaaaaaaa')
False
>>> print(a*21 is 'aaaaaaaaaaaaaaaaaaaaa')
False
通過上述 7 個例子,我們不難對 python 的字符串池化有個大概的認識,我們這里做個簡單的總結:
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。