我是Python的新手,所以我的问题可能看起来很明显。但根据W3Schools的说法,只有在引用同一对象的情况下,'is‘运算符下的两个变量才相同。所以我的问题是,为什么following返回True?我以为Python为它们创建了两个独立的内存位置?
a = 500
b = 500
print(a == b) # True
print(a is b) # True, why is this true?
发布于 2021-10-15 11:38:05
您确定这对值500有效吗?
Python 3.8.10 (default, Jun 2 2021, 10:49:15)
[GCC 9.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> a = 500
>>> b = 500
>>> a is b
False
>>> b = 100
>>> a = 100
>>> a is b
True
>>>
Python中的预分配
在Python中,Python3在启动时会保留一个整数对象数组,范围从-5到256。例如,对于int对象,使用名为NSMALLPOSINTS和NSMALLNEGINTS的marcos:
#ifndef NSMALLPOSINTS
#define NSMALLPOSINTS 257
#endif
#ifndef NSMALLNEGINTS
#define NSMALLNEGINTS 5
#endif
#if NSMALLNEGINTS + NSMALLPOSINTS > 0
/* References to small integers are saved in this array so that they
can be shared.
The integers that are saved are those in the range
-NSMALLNEGINTS (inclusive) to NSMALLPOSINTS (not inclusive).
*/
static PyIntObject *small_ints[NSMALLNEGINTS + NSMALLPOSINTS];
#endif
#ifdef COUNT_ALLOCS
Py_ssize_t quick_int_allocs;
Py_ssize_t quick_neg_int_allocs;
#endif
这是什么意思?这意味着当您从-5到256的范围创建int时,您实际上是在引用现有的对象。
参考:https://medium.com/@kjowong/everything-is-an-object-in-python-928f2a7d3e15
发布于 2021-10-15 11:37:25
这通常是一个优化问题。当你改变其中一个值(并占据内存中的2个位置)时,它将被拆分
发布于 2021-10-15 11:39:13
==和is运算符的区别相等运算符(==)比较两个操作数的值并检查值是否相等。而'is‘操作符检查两个操作数是否引用相同的对象(存在于相同的内存位置)
https://stackoverflow.com/questions/69589747
复制