Python:如何将自定义类成员与内置类型进行比较

标签 python list sorting comparison-operators

Python 新手,如果这是显而易见的,请原谅我。 假设我创建了一个自定义 class Foo,并创建了一个与 int 混合的 Foo() 实例列表,例如:

foo_list = [Foo() for _ in range(10)]
for i in range(10):
  foo_list.append(i)
# then the foo_list is mixed with Foo()s and ints

Foo 实例如何与 int 进行比较?基本上我的目标是使对上面的列表进行 sort() 成为可能。

最佳答案

您可以将 __lt____gt__ 方法添加到 Foo 类(小于和大于)来计算 Foo code> 对象小于或大于整数,当未提供关键函数时,sort 使用此功能

class Foo():

    def __lt__(self, other):
        if isinstance(other, int):
            return self._id < other
        elif isinstance(other, self.__class__):
            return self._id < other._id

    def __gt__(self, other):
        if isinstance(other, int):
            return self._id > other
        elif isinstance(other, self.__class__):
            return self._id > other._id

关于Python:如何将自定义类成员与内置类型进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57237429/

相关文章:

python - 如何将非线性模型转换为线性模型?

list - F#中元素的最优雅组合

python - 在 Python 3.4.3 中将两个字符串列表组合在一起一次

python - 如何将列表中名称相似的元素分组为 python 中的元组?

c++ - 快速排序 - Middle Pivot 实现奇怪的行为

python - 如何模拟 django 信号处理程序?

python - 绘制多类问题的 ROC 曲线

arrays - 如何计算两个重叠线性数据集之间的点?

php - 使用 <select> 对 mysql 数据库进行排序,但没有任何反应

python - 在 pandas 数据框中按列应用 seaborn 热图