Im trying to write a simple vending machine. I have Container class that contains items and class Items contains information like the prize and the amount. The ID indentifies the item. Every calling add item will increment ID by one, so that every item is unique. I would like to get the prize of given ID. So for example: I add item, it has ID=30, I give ID and it returns the prize of it.

I tried something like this, but it does not work:

from Item import Item

class Container:
    id = 30

    def __init__(self, objects=None):
        if objects is None:
            objects = {}
        self.objects = objects

    def add_object(self, obj: Item):
        self.objects.update({id: obj})
        Container.id = container.id + 1

    def get_length(self):
        return len(self.objects)

    def find_price_of_given_id(self, id):
        # return self.objects.get(id).get_price()
        pass


Cola = Item(20)
print(Cola.get_amount())
container = Container()
container.add_object(Cola)
print(container.objects.items())

Item class:

class Item:
    def __init__(self, price,amount=5):
        self.amount = amount
        self.price = price

    def get_price(self):
        return self.price

    def get_amount(self):
        return self.amount

I dont know why also print(container.objects.items()) returns dict_items([(<built-in function id>, <Item.Item object at 0x00000000022C8358>)]), why not ID = 30 + Item object

1 Answers

0
DroidX86 On Best Solutions
  1. id is the name of a builtin method. Don't use it as a variable name - leads to name confusion.

  2. You're assigning the id inside the container class but never giving it back, so that people can look up the item using the id.

  3. In python3, dict.items returns a dict_items iterator, so you need to iterate over it to get to the items within.

class Item:
    def __init__(self, price, amount=5):
        self.amount = amount
        self.price = price

    def get_price(self):
        return self.price

    def get_amount(self):
        return self.amount

    def __str__(self):
        return f"{self.amount} @ {self.price}"


class Container:
    item_id = 30

    def __init__(self, objects=None):
        if objects is None:
            objects = {}
        self.objects = objects

    def add_object(self, obj: Item):
        id_to_assign = Container.item_id
        self.objects.update({id_to_assign: obj})
        Container.item_id = Container.item_id + 1
        return id_to_assign

    def get_length(self):
        return len(self.objects)

    def find_price_of_given_id(self, item_id):
        return self.objects.get(item_id).get_price()


Cola = Item(20)
print(Cola.get_amount())
container = Container()
cola_id = container.add_object(Cola)
print(container.objects.items())
print(container.find_price_of_given_id(cola_id))

Output:

5
dict_items([(30, <__main__.Item object at 0x104444b00>)])
20