Reputation: 161
Attempting to create a program in python 3 that takes object(s) created from one class item
to another, shoppingCart
. The idea is to create a list of objects created by the item
class using the shoppingCart
class, while still being able to access attributes of the item
class such as price and quantity.
class item:
def __init__(self,n,p,q):
self.name = n
self.price = p
self.quantity = q
def show(self):
z = (str(self.name))
print(z)
self1 =("$")+(str(self.price))
print(self1)
def getName(self):
return self.name
def getPrice(self):
return ("$") + str(self.price)
def getQuantity(self):
return self.quantity
class shoppingCart:
def __init__(self, items):
self.items = []
def show(self):
print(self.items)
def addItem(self,item):
if item not in self.items:
self.items.append(item)
else:
item.q += 1
def deleteItem(self,item):
if item in self.items:
self.items.remove(item)
else:
return print("Not in Cart")
def checkOut (self):
total = 0
for i in self.items:
price = i[1]
total += price
return total
item1 = item("Chocolate",5 ,3)
item2 = item("Bacon",15,1)
item3 = item("Eggs",2,5)
c = shoppingCart([])
c.addItem(item1)
c.addItem(item2)
c.addItem(item3)
c.show()
print ("You have 3 items in your cart for a total of" (c.checkOut()))
c.removeItem(item3)
print ("You have 2 items in your cart for a total of" (c.checkOut()))
The above code currently creates two errors, firstly, the c.show is printing the IDs of the objects appended to the shopping cart. In addition, the checkOut
method creates an error regarding price = i[1]
saying that the item
object does not support indexing. Alternate solutions to this problem that still bares some resemblance to my original code will be welcome!
Upvotes: 0
Views: 10175
Reputation: 122106
First, c.show()
prints the list, but you haven't defined __str__
or __repr__
for your classes, so you're stuck with the default representation. Try e.g.
def __str__(self):
return str(self.name)
Then you can:
print(map(str, self.items))
Alternatively, use your item.show
:
for i in self.items:
i.show()
Second, in checkOut
, i
is an item
, which you can't index into. If you want its price, use dot notation: i.price
.
Upvotes: 1