Python:如何比较自定义类成员和内置类型

2024-04-29 13:47:25 发布

您现在位置:Python中文网/ 问答频道 /正文

对python还不熟悉,所以如果这是显而易见的,请原谅我。 假设我已经创建了一个自定义的class Foo,并列出了一个Foo()实例与int的混合列表,例如:

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进行比较?基本上,我的目标是使上面的列表成为可能。你知道吗


Tags: the实例in列表forfooisrange
2条回答

您可以将__lt____gt__方法添加到Foo类(小于和大于)中,这些类将Foo对象计算为小于或大于整数,这在未提供键函数时由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 sort()函数指定一个自定义函数,请参见文档中的the "key" function中的排序函数。你知道吗

例如,如果Foo有一个类似于字段bar的整数,则可以按其bar的值对Foo的每个实例进行排序,如下所示:

def custom_key_function(element):
    if isinstance(element, Foo):
        return element.bar
    else:
        return element  # element is just an int

foo_list.sort(key=custom_key_function)

注意isinstance的用法,它将告诉您某事是否是Foo的实例。你知道吗

我不知道你的Foo有哪些字段,但只要你的custom_key_functionFoo转换成可以与int相比的东西,你就应该很好。你知道吗

相关问题 更多 >