python - 为什么我的 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 并检查元素。
解决方案
__eq__
,对于任何类,应该处理三种情况:
self
并且other
是同一个对象self
并且other
是兼容的实例(直到鸭子类型:它们不需要是同一类的实例,但应根据需要支持相同的接口)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 == other
。other == self
except AttributeError:
return other == self
当然,您需要小心,这不会导致无限循环List
并type(other)
反复推迟到另一个。
推荐阅读
- oracle - Oracle 网络配置助手
- altair - Altair 彩色条形图按值未显示
- php - 如何在 Laravel 中上传多张图片
- nestjs - 何时在 NestJS 中使用 ExceptionFilter 与 BaseExceptionFilter?
- python - 如何在 tkinter 的同一张图上绘制多条线?
- javascript - 在 React 中将外部库从基于类迁移到函数式组件
- android - Unty中的Android状态栏显示
- javascript - 元素列表后缺少] - Javascript附加方法
- java - 从 InputStream 到并行 Stream
- javascript - 如何将文件 vuejs 组件导入 index.html?