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.