1

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?

5
  • if new_order_id in [order.id for order in orders] would be a simple way. Better to use a dictionary mapping id -> object instead though. Commented Sep 20, 2022 at 19:14
  • Yes! Instead of new_order_id use new_order.id where new_order is an instance of your new class. Commented Sep 20, 2022 at 19:15
  • @rdas , thank you, I will look into both of those options. Commented Sep 20, 2022 at 19:17
  • @mkrieger1, I don't want to process the JSON data to turn the new order into a class if I don't have to. It's not actually a variable called new_order_id. It looks more like order['order_number'] Commented Sep 20, 2022 at 19:19
  • You wrote "now I want to change the code so that order is a class" 🤷‍♂️ Now it's unclear to me what you want to do. Commented Sep 20, 2022 at 19:21

2 Answers 2

0
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
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.