class Shape():
def __init__(self, n_sides, name):
self.n_sides = n_sides
self.name = name
def generate_shapes():
return [Shape(4, 'square'), Shape(3, 'triangle'), Shape(4, 'rectangle')]
def generate_one_shape():
return Shape(4, 'square')
shapes = generate_shapes()
one_shape = generate_one_shape()
shapes.index(one_shape)
我得到如下错误,因为list.index()表面上比较了对象。
Traceback (most recent call last):
File "list_remove_object_by_value.py", line 14, in <module>
shapes.index(one_shape)
ValueError: <__main__.Shape instance at 0x7efffbbcec68> is not in list
我希望list.index(one_shape)将索引返回为0。
如何使用具有相同属性值的另一个类Shape实例有效地获取列表中Shape类实例的索引?
答案 0 :(得分:1)
只需定义一个__eq__
方法。
class Shape():
def __init__(self, n_sides, name):
self.n_sides = n_sides
self.name = name
def __eq__(self, other):
return (
isinstance(other, type(self)) and
other.n_sides == self.n_sides and
other.name == self.name
)
in
和index
这样的运营商会检查是否有任何项==
。这个__eq__
方法定义了使用这两个对象调用==
时会发生什么。默认情况下,它会检查它们是否完全相同,但这会检查它们是否都是Shape
,并且具有相同的n_sides
和name
。