您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

“ is”关键字的类型可能等效于Python中的相等运算符

“ is”关键字的类型可能等效于Python中的相等运算符

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 */
python 2022/1/1 18:50:02 有355人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶