0

In something like this

class Obj:
    def __init__(self, x, y):
        self.x = x
        self.y = y


li = [Obj(0, 0), Obj(0, 1), Obj(2, 3)]

print(Obj(2,3) in li)

I have a False output because even if x and y are the same it counts the object as a different instance. I can remedy using a loop inside the list and checking

if(2==o.x and 3==o.y):
    return True

Is there some cleaner way to get this without using a loop ?

MrSir
  • 576
  • 2
  • 11
  • 29
  • 4
    Implement an [`__eq__`](https://docs.python.org/3/reference/datamodel.html#object.__eq__) method in your class. – Aran-Fey Apr 24 '18 at 09:18
  • You must define `Obj.__eq__` – Olivier Melançon Apr 24 '18 at 09:18
  • Implement the special methods == and != in your object. – Mathieu Apr 24 '18 at 09:18
  • Alternatively, consider using [`namedtuple`](https://docs.python.org/3/library/collections.html#namedtuple-factory-function-for-tuples-with-named-fields) or the newer [data classes](https://hackernoon.com/a-brief-tour-of-python-3-7-data-classes-22ee5e046517). – jdehesa Apr 24 '18 at 09:19

2 Answers2

0

Special method for == and !=:

class Obj:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __eq__(self, Object):
        """ == comparison method."""
        return self.x == Object.x and self.y == Object.y

    def __ne__(self, Object):
        """ != comparison method."""
        return not self.__eq__(self, Object)
Mathieu
  • 5,410
  • 6
  • 28
  • 55
  • It depends on each particular case, but it is frequent to add a check like `isinstance(Object, Obj)` or `Object.__class__ == self.__class__` in the implementation of `__eq__` to avoid considering as equals objects of different classes with similarly-named attributes (although sometimes that may be the intended behavior). – jdehesa Apr 24 '18 at 09:23
  • True. Didn't bother with it for the example, but it should be added. – Mathieu Apr 24 '18 at 09:25
0

Implement a function __eq__ like below in your class.

def __eq__(self,  x,y):
     if self.x==x and self.y==y:
        return True

After that use list comprehension to traverse over the list of objects.

result = any(Obj(2,3) == i for i in obj_list )

Abhishake Gupta
  • 2,939
  • 1
  • 25
  • 34