python-为什么两个单独创建的不可变对象具有相同的id,而可变对象却具有不同的含义,而它们都引用相同的值?

这个问题已经在这里有了答案:            >            What’s with the Integer Cache inside Python?                                    1个
两个单独创建的可变列表具有不同的ID.

Python SHELL :(可变)

>>> mylist = ['spam', 'eggs']
>>> yourlist = ['spam', 'eggs']
>>> id(mylist), id(yourlist)
(49624456, 48910408)

虽然两个单独创建的不可变字符串具有相似的ID.

Python SHELL :(不可变)

>>> a = 10
>>> b = 10
>>> id(a), id(b)
(507099072, 507099072)

a和b引用相同的对象吗?如果没有,为什么ID相似?
mylist和yourlist是否引用不同的对象?如果是,为什么它们具有不同的ID.

解决方法:

Python会缓存一些小的字符串和数字:http://docs.python.org/2/c-api/int.html#PyInt_FromLong

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.

而且id(some_list)始终为您提供容器的地址-内存中的列表对象,而不是列表中的字符串!

上一篇:概念飘移-concept drift-Python小结


下一篇:xml文件中的特殊符号(&,<)的使用方法