Python 2.7 Python2.7如果未定义_ne__,则比较什么
在Python中有一种神奇的方法叫做Python 2.7 Python2.7如果未定义_ne__,则比较什么,python-2.7,Python 2.7,在Python中有一种神奇的方法叫做\uu_______,它在对象上被触发=比较 示例: class A(object): def __init__(self, a): self.a = a def __ne__(self, other): return self.a != other.a A(3) != A(3) # produces False A(3) != A(2) # produces True 问题: class A(object
\uu_______
,它在对象上被触发=代码>比较
示例:
class A(object):
def __init__(self, a):
self.a = a
def __ne__(self, other):
return self.a != other.a
A(3) != A(3) # produces False
A(3) != A(2) # produces True
问题:
class A(object):
def __init__(self, a):
self.a = a
def __ne__(self, other):
return self.a != other.a
A(3) != A(3) # produces False
A(3) != A(2) # produces True
如果未定义\uu ne\uu
,发动机罩下会发生什么情况
注意:在Python3.x中=代码>比较定义为\uuuu eq\uuu
返回的任何值的倒数
我认为对象ID是比较的,在本例中,假设我们没有单例,所有的=代码>比较必须返回True
。但是显然,不同环境中的同一代码产生了不同的结果,所以我想,还有一些东西可以比较,而不是对象ID。如果在类定义中不使用显式的\uune\ucode>,那么将使用继承的对象的\uune\ucode>。它的工作原理类似于以下代码(当然,原始代码是用C编写的):
因此,因为您正在比较用户定义的类,所以使用了id
这是源代码。查看slot\u tp\u richcompare
turkus的答案是正确的:如果没有指定\uuuu ne\uuuuuuuu()
方法,则返回\uuuu eq\uuuuuuu()
方法结果的倒数。CPython源代码的相关部分是slot\u tp\u richcompare()
:
如果未定义\uu-ne\uu()
,则调用相反的方法(在\u-Py\u-SwappedOp[op]
中定义为Py\u-EQ
,即\uu-EQ()
,用于Py\u-ne
)。classobject.c
中的注释显示了如果不定义\uuuu eq\uuu()
会发生什么:
/*如果没有\uuuu eq\uuuu
和\uuuuu cmp\uuuu
方法,我们在
地址。如果存在\uuuuuu eq\uuuuu
或\uuuu cmp\uuuuu
方法,则必须
是一个\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
*/
你从哪里拿的?你有这个功能的C实现的链接吗?这里的python代码很容易让人误解。如果未定义\uune\ucode>,Python2.7(与3.x相反)不会使用\uuueq\uuuu
(此代码暗示了这一点)。相反,它使用了id
(正如你所说的),甚至id\uuuuueq\uuuuu
都是独立于id定义的。如果我没有弄错的话,在\upy\u SwappedOp[op]
中定义的Py\u eq
的反面是Py\u eq
。交换只意味着交换左侧和右侧,所以a=b
被切换到b=a
。(请注意,aa
。因此,即使定义了\uuuuuueq\uuuuu
,Python2.7(与3.x相反)也不会将其用于\uuuuu ne\uuuuuu
。请参阅
static PyObject *
slot_tp_richcompare(PyObject *self, PyObject *other, int op)
{
PyObject *res;
if (Py_TYPE(self)->tp_richcompare == slot_tp_richcompare) {
res = half_richcompare(self, other, op);
if (res != Py_NotImplemented)
return res;
Py_DECREF(res);
}
if (Py_TYPE(other)->tp_richcompare == slot_tp_richcompare) {
res = half_richcompare(other, self, _Py_SwappedOp[op]);
if (res != Py_NotImplemented) {
return res;
}
Py_DECREF(res);
}
Py_INCREF(Py_NotImplemented);
return Py_NotImplemented;
}