0

messing around with Python and was building a simple text cart thing. when i try to iterate through the cart, using the defined __str__, it give me this error: 'CartItem' object is not subscriptable. i've tried to understand what this was talking about, but have failed to find anything on the matter.

here is the relevant code:

class CartItem:
  def __init__(self, name, price):
    self.name = name
    self.price = price
  def __str__(self):
    print(self.name + " --> " + self.price)
    return "-- item printed --\n"

class Cart:
  def __init__(self):
    self.items = []

  def __str__(self):
    if(len(self.items) > 0):
      index = 0
      for item in self.items:
        print(str(index) + ": " + item[index].name + ' --> ' + item[index].price)
        index += 1
    else:
      print("No Items in Cart")
    return "-- cart items printed--\n"

  def addItem(self, cartItem):
    self.items.append(cartItem)
    print (cartItem.name + ", costing $" + cartItem.price + ", has been added to cart\n")
    print(self.items)  # *should* print out the contents of the cart, but doesn't...

flarn = CartItem("flarn", "200.00")
print(flarn)
userCart = Cart()
userCart.addItem(flarn)
print(userCart)  # if i remove this line, i get [<__main__.CartItem object at 0x....>]??

can someone please explain what that error, 'CartItem' object is not subscriptable, means in context of this code? bonus point if you can explain the output removing print(userCart) returns.

WhiteRau
  • 818
  • 14
  • 32
  • 1
    You're both looping over and indexing items in the same loop, `item[index].name`. You don't need `index` and `item` is an item from the list you're looping over, not the list itself. – frippe Nov 16 '21 at 19:04

1 Answers1

3

The problem is item[index].name - CartItem is not subscriptable as the error states. You don't need to use index, you iterate over list. Also you can simplify your __str__() method.

Note that using print() inside the __str__() method is bad. Better construct a string to describe the cart and return it. Also should have __repr__ instead of __str__() for CartItem. It will be used when you print items in container like list Cart.items. Also you can use the string representation of the Item when you construct the Cart.__str__()

class CartItem:
    def __init__(self, name, price):
        self.name = name
        self.price = price
    def __repr__(self):
        return f'{self.name} --> {self.price}'


class Cart:
    def __init__(self):
        self.items = []

    def __str__(self):
        if self.items:
            return '\n'.join(f'{idx}: {item}' for idx, item in enumerate(self.items))
        return "Empty Cart"

    def addItem(self, cartItem):
        self.items.append(cartItem)
        print(f'{cartItem.name}, costing ${cartItem.price}, has been added to cart')
        print(self.items)  # *should* print out the contents of the cart, but doesn't...


userCart = Cart()
print(userCart)
flarn = CartItem("flarn", "200.00")
print(flarn)
userCart.addItem(flarn)
flarn = CartItem("flarn", "100.00")
print(flarn)
userCart.addItem(flarn)
print(userCart)

output:

Empty Cart
flarn --> 200.00
flarn, costing $200.00, has been added to cart
[flarn --> 200.00]
flarn --> 100.00
flarn, costing $100.00, has been added to cart
[flarn --> 200.00, flarn --> 100.00]
0: flarn --> 200.00
1: flarn --> 100.00
buran
  • 13,682
  • 10
  • 36
  • 61
  • fantastic! thank you. i learned so much from this. wow. i just have one remaining question: what the heck does the error *actually* mean?? can't find anything on `subscriptable`... – WhiteRau Nov 18 '21 at 20:27
  • also, the singe line ``for` loop was handy as heck! thanks again. :) – WhiteRau Nov 18 '21 at 20:30
  • 1
    [What does it mean if a Python object is "subscriptable" or not?](https://stackoverflow.com/q/216972/4046632) – buran Nov 18 '21 at 21:05
  • 1
    that is [generator expression](https://www.python.org/dev/peps/pep-0289/). Also have a look at e.g. [list comprehension](https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions). There are also dict comprehension and set comprehension – buran Nov 18 '21 at 21:07