不覆盖比较运算符的Python对象是否等于自身? [英] Does a Python object which doesn't override comparison operators equals itself?
问题描述
class A(object):
def __init__(self, value):
self.value = value
x = A(1)
y = A(2)
q = [x, y]
q.remove(y)
我想从列表中删除之前添加到该对象的特定对象,但仍然可以参考。我不要平等测试。我要进行身份测试。该代码似乎在CPython和IronPython中都可以使用,但是该语言是否可以保证这种行为还是仅仅是is幸?
I want to remove from the list a specific object which was added before to it and to which I still have a reference. I do not want an equality test. I want an identity test. This code seems to work in both CPython and IronPython, but does the language guarantee this behavior or is it just a fluke?
list.remove
方法文档是这样的:与del s [s.index(x)]
相同,这意味着将执行相等性测试。
The list.remove
method documentation is this: same as del s[s.index(x)]
, which implies that an equality test is performed.
如果您不覆盖 __ cmp __
, __ eq __
或 __ ne __
?
推荐答案
是。在您的示例中, q.remove(y)
将删除与 y
相等的对象的第一个匹配项。但是,定义类 A
的方式,您不应†拥有与 y
-除了也绑定到同一 y
实例的任何其他名称之外。
Yes. In your example q.remove(y)
would remove the first occurrence of an object which compares equal with y
. However, the way the class A
is defined, you shouldn't† ever have a variable compare equal with y
- with the exception of any other names which are also bound to the same y
instance.
文档的相关部分是此处:
如果没有
__ cmp __(),__ eq __()或定义了__ne __()
操作,通过对象标识(地址)比较类
实例。
If no
__cmp__(), __eq__() or __ne__()
operation is defined, class instances are compared by object identity ("address").
因此,对 A
实例的比较是通过身份(在CPython中实现为内存地址)进行的。在 y
的生存期内,其他任何对象都不能具有等于 id(y)
的身份,即只要您拥有对 y
的引用(如果要从列表中删除它,则必须这样做)。
So comparison for A
instances is by identity (implemented as memory address in CPython). No other object can have an identity equal to id(y)
within y
's lifetime, i.e. for as long as you hold a reference to y
(which you must, if you're going to remove it from a list!)
† 从技术上讲,仍然有可能在其他内存位置具有相等对象的对象- mock.ANY
就是这样一个例子。但是这些对象需要重写其比较运算符以强制执行结果。
† Technically, it is still possible to have objects at other memory locations which are comparing equal - mock.ANY
is one such example. But these objects need to override their comparison operators to force the result.
这篇关于不覆盖比较运算符的Python对象是否等于自身?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!