将两个变量与Python中在一行中声明的“is”运算符进行比较

2024-04-26 07:31:02 发布

您现在位置:Python中文网/ 问答频道 /正文

根据Documentation

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. So it should be possible to change the value of 1. I suspect the behaviour of Python in this case is undefined. :-)

所以以下行为是正常的。在

>>> a = 256
>>> b = 256
>>> a is b
True
>>> c = 257
>>> d = 257
>>> c is d
False

但是当我声明这样的两个变量时,我得到了真的-

^{pr2}$

我已经检查了e和f引用的对象的身份-

>>> id(e)
43054020
>>> id(f)
43054020

它们是一样的。在

我的问题是当我们用分号分隔来声明e和f时会发生什么?为什么它们引用同一个对象(尽管这些值超出了Python的整数对象数组的范围)?在

如果你能像对初学者那样解释它,那就更好了。在


Tags: oftheto对象inyouanid
1条回答
网友
1楼 · 发布于 2024-04-26 07:31:02

根据Python Data model这是一个意外的行为,这是一个实现细节:

Types affect almost all aspects of object behavior. Even the importance of object identity is affected in some sense: for immutable types, operations that compute new values may actually return a reference to any existing object with the same type and value, while for mutable objects this is not allowed. E.g., after a = 1; b = 1, a and b may or may not refer to the same object with the value one, depending on the implementation, but after c = []; d = [], c and d are guaranteed to refer to two different, unique, newly created empty lists. (Note that c = d = [] assigns the same object to both c and d.)

相关问题 更多 >