首页 > 解决方案 > 为什么我的 equal 方法总是返回 false?

问题描述

嗨,我刚开始在 python 中学习课程,我正在尝试实现一个基于数组的列表。这是我的类和初始化构造函数。

class List:

def __init__(self,max_capacity=50):
    self.array=build_array(max_capacity)
    self.count=0

但是,我编写了一个equals方法,如果列表等于另一个,则返回 true。但是,它总是返回 false。是的,我的附加方法正在工作。

 def __eq__(self,other):
    result=False
    if self.array==other:
        result=True
    else:
        result=False
    return result

这就是我测试它的方式,但它返回false?

a_list=List()
b_list=[3,2,1]
a_list.append(3)
a_list.append(2)
a_list.append(1)
print(a_list==b_list)

任何帮助,将不胜感激!

编辑:

在所有有用的建议之后,我发现我必须遍历 other 和 a_list 并检查元素。

标签: pythonpython-3.x

解决方案


__eq__,对于任何类,应该处理三种情况:

  1. self并且other是同一个对象
  2. self并且other是兼容的实例(直到鸭子类型:它们不需要是同一类的实例,但应根据需要支持相同的接口)
  3. self并且other没有可比性

牢记这三点,定义__eq__

def __eq__(self, other):
    if self is other:
        return True
    try:
        return self.array == other.array
    except AttributeError:
        # other doesn't have an array attribute,
        # meaning they can't be equal
        return False

请注意,这假定一个List实例应该与另一个对象进行比较,只要两个对象具有相同的array属性(无论这意味着什么)。如果这不是你想要的,你必须在你的问题中更具体。


最后一个选择是回退到other == self看看 type ofother是否知道如何将自己与您的List班级进行比较。相等应该是对称的,因此如果确实可以比较两个值是否相等,则应该产生相同的值self == otherother == self

except AttributeError:
    return other == self

当然,您需要小心,这不会导致无限循环Listtype(other)反复推迟到另一个。


推荐阅读