LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 208|回复: 0

对象比较

[复制链接]
发表于 2024-1-19 18:53:20 | 显示全部楼层 |阅读模式


richcmpfunc tp_richcompare;
tp_richcompare 处理句柄会在需要进行比较时被调用。 它类似于 富比较方法,例如 __lt__(),并会被 PyObject_RichCompare() 和 PyObject_RichCompareBool() 调用。

此函数被调用时将传入两个 Python 对象和运算符作为参数,其中运算符为 Py_EQ, Py_NE, Py_LE, Py_GE, Py_LT 或 Py_GT 之一。 它应当使用指定的运算符来比较两个对象并在比较操作成功时返回 Py_True 或 Py_False,如果比较操作未被实现并应尝试其他对象比较方法时则返回 Py_NotImplemented,或者如果设置了异常则返回 NULL。

下面是一个示例实现,该数据类型如果内部指针的大小相等就认为是相等的:

static PyObject *
newdatatype_richcmp(newdatatypeobject *obj1, newdatatypeobject *obj2, int op)
{
    PyObject *result;
    int c, size1, size2;

    /* code to make sure that both arguments are of type
       newdatatype omitted */

    size1 = obj1->obj_UnderlyingDatatypePtr->size;
    size2 = obj2->obj_UnderlyingDatatypePtr->size;

    switch (op) {
    case Py_LT: c = size1 <  size2; break;
    case Py_LE: c = size1 <= size2; break;
    case Py_EQ: c = size1 == size2; break;
    case Py_NE: c = size1 != size2; break;
    case Py_GT: c = size1 >  size2; break;
    case Py_GE: c = size1 >= size2; break;
    }
    result = c ? Py_True : Py_False;
    Py_INCREF(result);
    return result;
}
您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表