问题描述
两个单独创建的可变列表具有不同的ID.
Two individually created mutable list have different ids.
Python SHELL :(可变)
>>> mylist = ['spam', 'eggs']
>>> yourlist = ['spam', 'eggs']
>>> id(mylist), id(yourlist)
(49624456, 48910408)
两个单独创建的不可变字符串具有相似的ID.
While two individually created immutable strings have similar ids.
Python SHELL :(不可变)
>>> a = 10
>>> b = 10
>>> id(a), id(b)
(507099072, 507099072)
a
和b
是否引用同一对象?如果没有,为什么ID相似?mylist
和yourlist
是否引用了不同的对象?如果是,为什么它们具有不同的ID.
Is a
and b
referencing to a same object? If no, why ids are similar?Is mylist
and yourlist
referencing to different objects? If yes, why they have different ids.
推荐答案
Python会缓存一些小的字符串和数字: http://docs.python.org/2/c-api/int.html#PyInt_FromLong
Python caches some small strings and numbers: http://docs.python.org/2/c-api/int.html#PyInt_FromLong
id(some_list)
始终为您提供容器的地址-内存中列出对象,而不是列表中的字符串!
And id(some_list)
always gives you the address of container - list object in memory, not strings in list!
这篇关于为什么两个单独创建的不可变对象具有相同的id,而可变对象却具有不同的含义,而它们都引用相同的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!