python自定义类运算符重载

假设我有一个班级:

class Cat:
    def __init__(self, name = "default", age = 0):
        self.name = name
        self.age = age

我还有一个猫列表:

l = [Cat('Joe')]

现在我不能打电话给以下人员:

if 'Joe' in l: # the right syntax would be if Cat('Joe') in list

我需要重载哪个运算符才能通过其成员变量名识别类Cat的对象?

最佳答案 您必须定义__eq__方法,如下所示:

class Cat:

    def __init__(self, name = "default", age = 0):
        self.name = name
        self.age = age

    def __eq__(self, other):
        if isinstance(other, str):
            return self.name == other
        elif isinstance(other, Cat):
            return self.name == other.name

这样当你运行支票时:

l = [Cat('Joe')]

'Joe' in l
#True
点赞