官方文檔
A Python program is constructed from code blocks. A block is a piece of Python program text that is executed as a unit. The following are blocks: a module, a function body, and a class definition. Each command typed interactively is ablock. A script file (a file given as standard input to the interpreter or specified as a command line argument to theinterpreter) is a code block. A script command (a command specified on the interpreter command line with the ‘-c‘ option) is a code block. The string argument passed to the built-in functions eval() and exec() is a code block.A code block is executed in an execution frame. A frame contains some administrative information (used for debugging)and determines where and how execution continues after the code block’s execution has completed.
意思是說
Python程序是由代碼塊構造的。塊是一個python程序的文本,他是作為一個單元執行的。代碼塊:一個模塊,一個函數,一個類,一個文件等都是一個代碼塊。而作為交互方式輸入的每個命令都是一個代碼塊。對於每個def function()都是一個單獨的代碼塊
代碼塊的緩存機制
Python在執行同一個代碼塊的初始化對象的命令時,會檢查是否其值經存在,如果存在,會將其重用。換句話說:執行同一個代碼塊時,遇到初始化對象的命令時,他會將初始化的這個變量與值存儲在一個字典中,在遇到新的變量時,會先在字典中查詢記錄,如果有同樣的記錄那么它會重復使用這個字典中的之前的這個值。所以在給出的例子中,文件執行時(同一個代碼塊)會把i1、i2兩個變量指向同一個對象,滿足緩存機制則他們在內存中只存在一個,最直接的表現就是:id相同。
代碼塊的緩存機制的好處
能夠提高一些字符串,整數處理人物在時間和空間上的性能;需要值相同的字符串,整數的時候,直接從‘字典’中取出復用,避免頻繁的
創建和銷毀,提升效率,節約內存。
小數據池
The current implementation keeps an array of integer objects for all integers between -5 and 256, when you create an int in thatrange you actually just get back a reference to the existing object. So it should be possible to change the value of 1. I suspectthe behaviour of Python in this case is undefined.Incomputer science, string interning is a method of storing only onecopy of each distinct string value, which must be immutable.Interning strings makes some stringprocessing tasks more time- or space-efficient at the cost of requiring moretime when the stringis created or interned. The distinct values are stored ina string intern pool.
意思是說
Python自動將-5~256的整數進行了緩存,當你將這些整數賦值給變量時,並不會重新創建對象,而是使用已經創建好的緩存對象。python會將一定規則的字符串在字符串駐留池中,創建一份,當你將這些字符串賦值給變量時,並不會重新創建對象, 而是使用在字符串駐留池中創建好的對象。
其實,無論是緩存還是字符串駐留池,都是python做的一個優化,就是將~5-256的整數,和一定規則的字符串,放在一個‘池’(容器,或者字典)中,無論程序中那些變量指向這些范圍內的整數或者字符串,那么他直接在這個‘池’中引用,言外之意,就是內存中之創建一個。
這樣做的好處是:
能夠提高一些字符串,整數處理人物在時間和空間上的性能;需要值相同的字符串,整數的時候,直接從‘池’里拿來用,避免頻繁的創建和銷毀,提升效率,節約內存。
對於int
小數據池的范圍是-5~256 ,如果多個變量都是指向同一個(在這個范圍內的)數字,他們在內存中指向的都是一個內存地址。
對於str
1
字符串的長度為0或者1,默認都采用了駐留機制(小數據池)。
2
字符串的長度>1,且只含有大小寫字母,數字,下划線時,才會默認駐留。
3
用乘法得到的字符串:
乘數為1時:僅含大小寫字母,數字,下划線,默認駐留。含其他字符,長度<=1,默認駐留。含其他字符,長度>1,默認駐留。
乘數>=2時:僅含大小寫字母,數字,下划線,總長度<=20,默認駐留。
對於bool
無非是Ture
/ False
無論你創建多少個變量指向True,False,那么他在內存中只存在一個, None 更是全局唯一的對象。
可以自由的制定在緩存中駐留的資源
from sys import intern
a = intern('monkey@'*100)
b = intern('monkey@'*100)
print(a is b)
指定駐留是你可以指定任意的字符串加入到小數據池中,讓其只在內存中創建一個對象,多個變量都是指向這一個字符串。