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/