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 类实例的索引?
只需定义一个__eq__
方法。
class Shape():
def __init__(self, n_sides, name):
self.n_sides = n_sides
self.name = name
def __eq__(self, other):
"""self == other"""
if isinstance(other, Shape):
# We can only compare if `other` is a Shape as well
return self.n_sides == other.n_sides and self.name == other.name
return NotImplemented
def __ne__(self, other):
"""self != other"""
eq = Shape.__eq__(self, other)
return NotImplemented if eq is NotImplemented else not eq
操作员喜欢in
和index
做的是检查==
彼此之间是否有任何项目。这个__eq__
方法定义了当==
用这两个对象调用时会发生什么。默认情况下,它会检查它们是否完全相同,但这会检查它们是否都是Shape
s,并且是否具有相同的n_sides
和name
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句