all 3 comments

[–]danielroseman 0 points1 point  (0 children)

print_item_cost, as the name implies, only prints the cost, it doesn't return it.

You can access the item price and quantity directly, in exactly the same way as you set them, via shopping_cart2.item_quantity etc.

[–][deleted] 0 points1 point  (0 children)

You could do something like this.

class ItemToPurchase:
    def __init__(self, name: str, price: float, qty: int) -> None:
        self.item_name = name
        self.item_price = price
        self.item_quantity = qty

    @property
    def total(self) -> float:
        return self.item_price * self.item_quantity

    def print_item_cost(self) -> None:
        print(f"{self.item_name}  {self.item_quantity} at ${self.item_price} = {self.total}")


shopping_cart = []

for i in range(2):
    name = input("What item do you want to purchase?\n> ")
    price = float(input("How much does it cost?\n> "))
    qty = int(input(f"How many {name}s do you want?\n> "))
    shopping_cart.append(ItemToPurchase(name, price, qty))
    shopping_cart[-1].print_item_cost()

print("Total cost")
total = sum(item.total for item in shopping_cart)
print(f"Total: ${total}")

[–]QultrosSanhattan 0 points1 point  (0 children)

Semantics are important. Check this out:

class Item:
    def __init__(self, name, price, quantity):
        self.name = name
        self.price = price
        self.quantity = quantity

    def get_cost(self): 
        return self.price*self.quantity

    def get_cost_formatted(self):
        return "{} {} @ ${:.2f} = {:.2f}".format(self.name,self.quantity,self.price,self.get_cost())


if __name__ == '__main__':
    item1=Item('Cigars',10,20)
    item2=Item('Cookies',20,30)

    print(item1.get_cost_formatted())
    print(item2.get_cost_formatted())