繁体   English   中英

Python 如何知道 integer object 是之前创建的并给出相同的参考(即使值> 256)?

[英]How does Python know that an integer object was created before and gives the same reference (even for values > 256)?

例如

a = 12345  # id(a) = 140127713009936
a = 6789  # id(a) = 140127713010448
b = 12345  # id(b) = 140127713009936

How is it possible that Python remembers somehow that integer object with value 12345 was created before and gives reference to it instead of creating new object? 我了解它对于值 -5 到 256 的工作原理,但为什么它甚至可以工作更大的数字(也适用于字符串,尽管我不知道它是否是相同的机制)?

在 python 中(出于优化原因),如果您有两个具有相同值的对象,则一切都是指针,因此,python 会将每个对象的指针指向包含该值的相同位置。

见: https://realpython.com/pointers-in-python/

How python knows if the object were early created: python map the name of each object to a memory address that the value exists there.

如果该值不存在,python 创建一个新值。

希望你觉得它有帮助!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM