'list.remove'函数不按值比较对象
假设代码是:
class item:
def __init__(self, a, b):
self.feild1 = a
self.field2 = b
a = item(1,4)
b = item(1,4)
l = [a]
l.remove(b) # doesn't remove l[0]
答案 0 :(得分:3)
由于未提供__eq__
实现,因此您的类继承了object
的方法。 object.__eq__
不比较attribute的值,它只是检查看id(a) == id(b)
。您需要编写自己的__eq__
:
class item:
def __init__(self, a, b):
self.field1 = a
self.field2 = b
def __eq__(self, other):
if not isinstance(other, item):
return NotImplemented
return self.field1 == other.field1 and self.field2 == other.field2
a = item(1,4)
b = item(1,4)
l = [a]
l.remove(b)
print(l)
# []