问题描述
t = (1,2,3)
t1 = (1,2,3)
print(id(t))
print(id(t1))
以上代码行在 Python 中的脚本模式下给出了相同的地址,但在交互模式下它输出不同的地址.谁能解释一下这是什么原因?
The above lines of code gives the same addresses in script mode in Python, but in interactive mode it outputs different addresses. Can anyone explain the reason for this?
推荐答案
在编译脚本时,编译器可以搜索所有等价的元组并生成代码以对所有元组使用相同的引用.
When the script is being compiled, the compiler can search for all the equivalent tuples and generate code to use the same reference for all of them.
但在交互模式下,它需要保留所有元组的缓存,以便它可以搜索先前的等效元组并返回对它的引用,而不是每次都创建一个新元组.交互式解释器不这样做.
But in interactive mode, it would need to keep a cache of all tuples so it could search for a previous equivalent tuple and return a reference to it, rather than creating a new tuple each time. The interactive interpreter doesn't do this.
如果将两个变量分配在同一行,实际上会得到相同的元组.
If you assign both variables on the same line, you actually get the same tuple.
t = (1, 2, 3); t1 = (1, 2, 3)
这大概是因为它为每个输入运行编译器,所以它可以做完整的分析和优化.
This is presumably because it's running the compiler for each input, so it can do the full analysis and optimization.
这篇关于尽管元组是不可变的,但它们以交互模式存储在不同的地址中.为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)