根据对象状态的相等获取列表中的对象的索引

问题描述:

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类实例的索引列表中的有效利用具有相同类形状的另一个实例属性值?

+1

尝试为'形状'定义'__eq__'# – Hamms

+0

如果有*多个*这样的元素或*无*,该怎么办? –

+0

如果有多个这样的实例,我仍然只需要列表中第一个这样的元素的索引。 –

只需定义一个__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 
     ) 

是什么样的inindex运营商做的是检查,如果有任何物品==对方。这__eq__方法定义了==与两个对象调用时会发生什么。默认情况下,它会检查它们是否完全相同,但是这会检查它们是否都是Shape s,并且具有相同的n_sidesname

+1

当你在它的时候,你还应该提供'__ne__'和'__hash__',或者设置'__hash__ = None'来让对象不可哈哈。 (Python 3会自动处理其中的一些内容,但是Python 2不会死一会儿。) – user2357112

+0

如果其中一个类属性是浮点数,这仍然有效吗? –

+0

@AdityaBarve他们必须完全相同。一个常见的伎俩是不用'float_a == float_b',你可以通过'abs(float_a - float_b) Artyer