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文件运行