Python就是有这种操作

发现Python有这个操作的是因为再看Fluent Python这本书并且在Python解释器中运行一小段代码的发现这种操作的,现在记录一下这个过程。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
>>> t1 = (1, 2, 3)
>>> l1 = [1, 2, 3]
>>> id(t1)
140129474189664
>>> id(l1)
140129446358480
>>> t1
(1, 2, 3)
>>> l1
[1, 2, 3]
>>> a[0] is b[0]
True
>>> a[1] is b[1]
True
>>> a[2] is b[2]
True

是的,每一次创建一个对象的时候,都会为这个对象一个新的内存地址。但总有些情况是例外的。后来去Google了一发,然后看到第一条Stack Overflow

下面引用Kasramvd说的一段话:

Immutable objects don’t have the same id, and as a mater of fact this is not true for any type of objects that you define separately. Every time you define an object in Python, you’ll create a new object with a new identity.

But there are some exceptions for small integers (between -5 and 256) and small strings (interned strings, with a special length (usually less than 20 character)) which are singletons and have same id (actually one object with multiple pointer).

意思就是说,当整形数(small integers)在-5到256这个区间的时候,或者是字符串(small strings)是单例,这些字符串有特别长度(通常小于20个字符),那么它们就有相同的id,即相同的内存地址。

参考内容