为 Python C 扩展类型定义 __eq__

dar*_*ine 3 c python

我在尝试实现__eq__我作为 C 扩展编写的 Rect 类时遇到问题。我尝试定义一个名为 的方法__eq__,但 Python 似乎覆盖了它。

static PyObject *
Rect___eq__(Rect *self, PyObject *other)
{
    Rect *rect = (Rect *) other;
    if (self->x != rect->x || self->y != rect->y || 
            self->width != rect->width || self->height != rect->height) {
        Py_RETURN_FALSE;
    } else {
        Py_RETURN_TRUE;
    }
}

static PyMethodDef Rect_methods[] = {
    {"__eq__", (PyCFunction)Rect___eq__, METH_VARARGS,
     "Compare Rects" },
    {NULL}  /* Sentinel */
};
Run Code Online (Sandbox Code Playgroud)

似乎无论我做什么,Python 默认都是“is”行为:

>>> a = Rect(1, 2, 3, 4)
>>> b = Rect(1, 2, 3, 4)
>>> a == b
False
>>> a == a
True
Run Code Online (Sandbox Code Playgroud)

cas*_*evh 5

使用 C 中定义的新类型时,需要定义 tp_richcompare。下面是一个类型的丰富比较的实现,该类型总是比所有其他类型(除了它自己)进行比较:

static PyObject *
Largest_richcompare(PyObject *self, PyObject *other, int op)
{
    PyObject *result = NULL;

    if (UndefinedObject_Check(other)) {
        result = Py_NotImplemented;
    }
    else {
        switch (op) {
        case Py_LT:
            result = Py_False;
            break;
        case Py_LE:
            result = (LargestObject_Check(other)) ? Py_True : Py_False;
            break;
        case Py_EQ:
            result = (LargestObject_Check(other)) ? Py_True : Py_False;
            break;
        case Py_NE:
            result = (LargestObject_Check(other)) ? Py_False : Py_True;
            break;
        case Py_GT:
            result = (LargestObject_Check(other)) ? Py_False : Py_True;
            break;
        case Py_GE:
            result = Py_True;
            break;
        }
    }

    Py_XINCREF(result);
    return result;
}
Run Code Online (Sandbox Code Playgroud)

如果您使用的是 Python 3.x,请将其添加到类型对象中,如下所示:

(richcmpfunc)&Largest_richcompare,       /* tp_richcompare */
Run Code Online (Sandbox Code Playgroud)

如果您使用的是 Python 2.x,则需要执行一个额外的步骤。在 Python 2.x 的生命周期中添加了丰富的比较,对于某些 Python 版本,C 扩展可以选择定义 tp_richcomare。要通知 Python 2.x 您的类型实现了丰富的比较,您需要通过 Py_TPFLAGS_HAVE_RICHCOMPARE 中的 or-ing 来修改 tp_flags。

Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_RICH_COMPARE,        /* tp_flags */
Run Code Online (Sandbox Code Playgroud)