为什么在同一行中创建的两个对象具有相同的对象,但这与列表不同?

Why two objects created in same line are having same objects but this is not same with lists?

在下面的代码中,a 和 b 具有相同的 ID

>>> a,b=470,470
>>> id(a)
32404032
>>> id(b)
32404032

但这里没有,

>>> a = 470
>>> b = 470
>>> id(a)
32403864
>>> id(b)
32344636

而且如果在同一行中创建相同的列表对象则给出不同的 id

>>> a,b=[1,2], [1,2]
>>> id(a)
32086056
>>> id(b)
32653960
>>>

为什么在同一行创建的具有相同整数的变量具有相同的id,而在不同行创建时却不同,这与列表也不同。

是的,对于 immutable 对象,编译器将创建 constants 并重新使用它们。但是,您不能对列表等可变对象执行此操作,因为如果您通过一个或另一个引用进行更改,那么您将操纵 相同的对象

您可以通过查看代码对象的 co_consts 属性来提取常量;获得其中之一的最简单方法是使用 compile() 函数:

>>> compile("a,b=470,470", '', 'single').co_consts
(470, None, (470, 470))

在交互式解释器中,单独的行被单独编译,所以有单独的常量。在单独的 Python 脚本中,每个范围都有自己的常量,允许更广泛的共享。在交互式解释器中,创建一个函数或 class 以使用它们自己的常量获得单独的作用域:

>>> def foo():
...     a = 470
...     b = 470
...     return id(a) == id(b)
...
>>> foo()
True
>>> foo_code = compile('''\
... def foo():
...     a = 470
...     b = 470
...     return id(a) == id(b)
... ''', '', 'single')
>>> foo_code = compile('''
... def foo():
...     a = 470
...     b = 470
...     return id(a) == id(b)
... ''', '', 'single')
>>> foo_code.co_consts
(<code object foo at 0x1018787b0, file "", line 2>, None)
>>> foo_code.co_consts[0].co_consts  # constants for the foo function code object
(None, 470)

这些是实施细节(优化),您不应依赖它们。