python程序是由代碼塊構成的,一個代碼塊的文本做爲pythont程序執行的單元python
官方文檔: 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 a block. A script file (a file given as standard input to the
interpreter or specified as a command line argument to the interpreter) 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.
一個代碼塊:編程
經過id()能夠查看到一個變量表示的值在內存中的地址緩存
s = "hello" print(id(s)) # 2305859175064
若是內存地址相同,則值必定是相等的,若是值相等,則不必定同一對象編程語言
a = 100 b = 100 print(a is b) # True print(a == b) # True
a = 1000 b = 1000 print(a == b) # True print(a is b) # False 在command命令下爲False, 在.py文件中(例如pycharm中)獲得的結果爲True。(詳情見下面)
優勢:可以提升字符串、整數的處理速度。省略了建立對象的過程。函數
缺點:在"池"中建立或者插入新的內容會花費更多的時間。ui
1.整數this
官方文檔: The current implementation keeps an array of integer objects for all integers between -5 and 256, when you create an int in that range you
actually just get back a reference to the existing object. So it should be possible to change the value of 1. I suspect the behavior of Python in
this case is undefined.
2.字符串spa
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 string is created or interned. The distinct values are
stored ina string intern pool. –引⾃自維基百科
在代碼塊內緩存機制是不同的:debug
注意:對於同一個代碼塊,只針對單純建立變量,纔會採用緩存機制,對於建立變量並同時作相關運算,則無。code
a = 1000 b = 1000 print(id(a)) # 2135225709680 print(id(b)) # 2135225709680 print(a is b) # True .py文件運行
a = 1000 b = 10*100 print(id(a)) # 1925536396400 print(id(b)) # 1925536643952 print(a is b) # False .py文件運行
a = 5*5 b = 25 print(id(a)) # 1592487712 print(id(b)) # 1592487712 print(a is b) # True .py文件運行
a = "Incomputer science, string interning is a method of storing only onecopy of each distinct string value" b = "Incomputer science, string interning is a method of storing only onecopy of each distinct string value" print(id(a)) # 2926961023256 print(id(b)) # 2926961023256 print(a is b) # True .py文件運行