gpt4 book ai didi

python - 值相等或引用相等的比较运算符 "=="?

转载 作者:行者123 更新时间:2023-12-05 01:55:12 25 4
gpt4 key购买 nike

很多教程都说==比较运算符用于值相等,例如 answer , 引用:

  • == is for value equality. Use it when you would like to know if two objects have the same value.
  • is is for reference equality. Use it when you would like to know if two references refer to the same object.

但是,我发现 Python doc说:

x==y calls x.__eq__(y). By default, object implements __eq__() by using is, returning NotImplemented in the case of a false comparison: True if x is y else NotImplemented."

这似乎是 == 的默认行为运算符是比较引用质量,如 is运算符,这与这些教程所说的相矛盾。

那么我到底应该用什么==为了?值相等还是引用相等?或者这仅取决于您如何实现 __eq__方法。


我认为 Value comparisons 的文档清楚地说明了这个问题:

The operators <, >, ==, >=, <=, and != compare the values of two objects. The value of an object is a rather abstract notion in Python. Comparison operators implement a particular notion of what the value of an object is. One can think of them as defining the value of an object indirectly, by means of their comparison implementation.

The behavior of the default equality comparison, that instances with different identities are always unequal, may be in contrast to what types will need that have a sensible definition of object value and value-based equality. Such types will need to customize their comparison behavior, and in fact, a number of built-in types have done that.

The default behavior for equality comparison (== and !=) is based on the identity of the objects. Hence, equality comparison of instances with the same identity results in equality, and equality comparison of instances with different identities results in inequality. A motivation for this default behavior is the desire that all objects should be reflexive (i.e. x is y implies x == y).

它还包含一个列表,描述了最重要的内置类型(如数字、字符串和序列等)的比较行为。

最佳答案

这完全取决于 __eq__ 的作用。 object 类型的默认 __eq__ 行为类似于 is。一些内置数据类型使用它们自己的实现。例如,如果两个列表的所有值都相等,则两个列表相等。你只需要知道这一点。

关于python - 值相等或引用相等的比较运算符 "=="?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70347051/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com