该is
运营商的测试,如果两个物体在物理上是相同的,这意味着如果他们在内存中的同一地址。也可以使用以下id()
功能进行测试:
>>> a = 1
>>> b = 1
>>> a is b
True
>>> id(a) == id(b)
True
在==
另一方面,运营商,测试对语义平等。也可以通过实现该__eq__()
功能来由自定义类覆盖。在语义上,如果两个不同的列表的元素都相等,则它们是相等的,但实际上它们将是不同的对象。
不可变的类型(例如字符串和元组)可能会被Python实现合并,因此两个文字字符串对象实际上在物理上是相同的。但这并不意味着您可以始终使用它们is
来比较这些类型,如以下示例所示:
>>> "foobar" is "foobar" # The interpreter kNows that the string literals are
True # equal and creates only one shared object.
>>> a = "foobar"
>>> b = "foobar"
>>> a is b # "foobar" comes from the pool, so it is still the same object.
True
>>> b = "foo" # Here, we construct another string "foobar" dynamically that is
>>> b += "bar" # physically not the same as the pooled "foobar".
>>> a == b
True
>>> a is b
False
Python中的赋值始终将对对象的引用绑定到变量名,并且从不暗示任何副本。
类似于C,想想Python变量始终是指针:
>>> a = 1
>>> b = a
>>> a = 2
>>> b
1
大致相当于:
const int ONE = 1;
const int TWO = 2;
int *a = &ONE;
int *b = a; /* b points to 1 */
a = &TWO; /* a points to 2, b still points to 1 */