Home > Software design >  Check if value in an array of objects
Check if value in an array of objects

Time:09-21

I recently wrote a code that had all attributes stored separately in different arrays like

order_id = []
order_name = []
order_products = []
order_total = []

And when importing new orders through an API request I would check if I already have that order by doing

if new_order_id in order_id:
    # do new order stuff

Now I want to change the code so that order is a class that has id, name, products and total as attributes and all orders are stored in an array called orders. Is there an easy way to check if the new order id matches the id of any order objects in the orders array?

CodePudding user response:

class oder():
    def __init__(self, id, name, products, total):
        self.id = id
        self.name = name
        self.products = products
        self.total = total
    
oders=[]# Class objects are here

if new.id in [oder.id for oder in oders]:
    #Place an Order

CodePudding user response:

One way to test for the existence of an object in a container is to give the object a "value" by way of the __eq__ magic method. For example:

class Order:
    def __init__(self, id):
        self.order_id = id
    def __eq__(self, other):
        return self.order_id == other

order_list = [Order('123'), Order('456')]

Then you can test for order numbers:

>>> '123' in order_list
True
>>> '345' in order_list
False
  • Related