You need to add the equality attribute to your object. To get the attributes of objects, you can pass the attribute names to operator.attrgetter , which returns a tuple of received attributes, then you can compare the tuples. You can also use the __dict__ attribute, which will give you the module namespace as a dictionary object. Then you can get the names of the attributes that you want to compare with objects based on them.
from operator import attrgetter class Product: def __init__(self, price, height, width): self.price = price self.height = height self.width = width def __eq__(self, val): attrs = ('width', 'price', 'height') return attrgetter(*attrs)(self) == attrgetter(*attrs)(val) def __ne__(self, val): attrs = ('width', 'price', 'height') return attrgetter(*attrs)(self) != attrgetter(*attrs)(val)
Edit:
As @Ashwini is mentioned in a comment based on the python wiki:
There are no implied relationships between comparison operators. true x==y does not mean that x!=y is false. Accordingly, when defining __eq__() , you should also define __ne__() so that the operators behave as expected.
So, as a more complete way, I also added the __ne__ attribute to the object. Which will return True if one of the attributes is not equal to it relative to one in another object.
Demo:
prod_list = [] prod1 = Product(3, 3, 3) prod_list.append(prod1) prod2 = Product(3, 3, 2) prod_list.append(prod2) prod3 = Product(3, 3, 3) print prod3 in prod_list True prod3 = Product(3, 3, 5) print prod3 in prod_list False