为什么两个单独创建的不可变对象具有相同的id,而可变对象却具有不同的含义,而它们都引用相同的值? [英] Why two individually created immutable objects have same id and mutable objects have different while both refer to same values?

查看:125
本文介绍了为什么两个单独创建的不可变对象具有相同的id,而可变对象却具有不同的含义,而它们都引用相同的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

两个单独创建的可变列表具有不同的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)

ab是否引用同一对象?如果没有,为什么ID相似? mylistyourlist是否引用了不同的对象?如果是,为什么它们具有不同的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会缓存一些小的字符串和数字:

Python caches some small strings and numbers: http://docs.python.org/2/c-api/int.html#PyInt_FromLong

当前实现为所有对象保留一个整数对象数组 在-5到256之间的整数,当您在该范围内创建int时, 实际上只是获取对现有对象的引用.

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)始终为您提供容器的地址-内存中列出对象,而不是列表中的字符串!

And id(some_list) always gives you the address of container - list object in memory, not strings in list!

这篇关于为什么两个单独创建的不可变对象具有相同的id,而可变对象却具有不同的含义,而它们都引用相同的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆