Check if the object (with certain property values) is not in the list

I am new to Python. I am using Python v2.7.

I defined a simple Product class:

 class Product: def __init__(self, price, height, width): self.price = price self.height = height self.width = width 

Then I created a list, which is then added with the Product object:

 # empty list prod_list = [] # append a product to the list, all properties have value 3 prod1 = Product(3,3,3) prod_list.append(prod1) 

Then I created another Product object that sets the same initialization values ​​(all 3):

 prod2 = Product(3,3,3) 

Then I want to check if prod_list contains Product object, which has a price = 3, width = 3 and height = 3, by:

 if prod2 not in prod_list: print("no product in list has price=3, width=3 & height=3") 

I expect the message to not be printed, but it is printed. In Python, how can I check if there are any objects with specific property values ​​in the list?

+6
source share
1 answer

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 
+7
source

All Articles