有没有一种方法可以按值删除列表中的对象?

时间:2018-10-12 16:43:28

标签: python python-3.x

'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]

1 个答案:

答案 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)
# []