[英]Is list's variable is an object in Python?
a = [1,2,3]
b = [1,2,3]
I understand a is b
is false but i can't understand a is [1,2,3]
is false我知道
a is b
是假的,但我不明白a is [1,2,3]
是假的
I learned variable is like nickname for objects like x = 2
and id(x) == id(2)
我了解到变量就像
x = 2
和id(x) == id(2)
这样的对象的昵称
but id(a)
is not as same as id(b)
...但
id(a)
与id(b)
不同...
In this case, a is an object?在这种情况下,a 是 object? not a variable?
不是变量?
Variables are references to objects.变量是对对象的引用。
a
does not reference the same object as b
. a
没有引用与b
相同的 object 。 Even though the two objects are the same they have unique addresses in memory and do not depend on each other.尽管这两个对象相同,但它们在 memory 中具有唯一的地址,并且不相互依赖。
>>> a = b = [1,2,3]
>>> c = [1,2,3]
>>> print(a is b)
True
>>> print(a is c or b is c)
False
>>> a.remove(1)
>>> print(a)
[2, 3]
>>> print(b)
[2, 3]
>>> print(c)
[1, 2, 3]
In the case of the x = 2
and id(x) == id(2)
integers are immutable and in CPython id
is simply the location of an object in memory.在
x = 2
和id(x) == id(2)
的情况下,整数是不可变的,而在 CPython 中, id
只是 memory 中 object 的位置。 Integers are always the same so storing the same integer several times at different addresses would be a waste of memory.整数总是相同的,因此在不同的地址多次存储相同的 integer 将浪费 memory。
However, in general DO NOT use integers with is
operator as it can lead to different results across different python implementations.但是,通常不要将整数与
is
运算符一起使用,因为它可能导致不同 python 实现的结果不同。
Everything in Python is an object. Python 中的所有内容都是 object。
a is b
evaluates to false because, as you know, they are not the same object. a is b
评估为假,因为如您所知,它们与 object 不同。 They are both instances of the List
class, therefore having different locations in memory, and being completely separate in every way except their class structure, or blueprint, as you can think of it.它们都是
List
class 的实例,因此在 memory 中具有不同的位置,并且除了它们的 class 结构或蓝图外,它们在各个方面都是完全独立的。 id(a)
and id(b)
will reflect this, they are not the same object and will therefore not share an ID. id(a)
和id(b)
将反映这一点,它们不是同一个 object,因此不会共享一个 ID。 This is a reference to their location in memory, and while IDs are not referenced pointers, they are similar in that they describe their not being the same.这是对它们在 memory 中位置的引用,虽然 ID不是引用的指针,但它们的相似之处在于它们描述了它们的不同之处。
>>> a = [1, 2, 3]
>>> b = [1, 2, 3]
>>> id(a) == id(b)
False
>>> # the below is an example, every session will result in a different ID,
>>> # as it's being stored at a unique mem location each time
>>> id(a)
2770873780160
>>> id(b)
2770873412800
>>> id(a) - id(b) # simply to show the difference in location.
367360
double equals vs is in python 双等于 vs 在 python
https://www.tutorialspoint.com/difference-between-and-is-operator-in-python https://www.tutorialspoint.com/difference-between-and-is-operator-in-python
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.