Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ''' Lab 2 Q 3 '''
- class Product:
- def __init__(self, code, desc, price):
- self._code = code
- self._desc = desc
- self._price = price
- @property
- def code(self):
- return self._code
- @property
- def price(self):
- return self._price
- def __str__(self):
- return "{} ${}".format(self._code, self._price)
- ######################
- class CartItem:
- def __init__(self, prod, qty):
- self._prod = prod
- self._qty = qty
- @property
- def pCode(self):
- return self._prod.code
- @property
- def qty(self):
- return self._qty
- @qty.setter
- def qty(self, value):
- if value >= 0:
- self._qty = value
- @property
- def cost(self):
- return self._prod.price * self._qty
- def __str__(self):
- return "{} {} at ${}".format(self._prod.code, self._qty, self.cost)
- '''
- Sorry, please add one property/method to CartItem class.
- OK everyone??
- '''
- ######################
- class ShoppingCart:
- def __init__(self, shopperName):
- self._shopper = shopperName # As stated in the questioni
- self._items = {} # No CartItem initially
- def add(self, cartItem):
- if cartItem.pCode in self._items.keys(): # Already in the shopping cart
- print("Item already exist")
- else:
- self._items[cartItem.pCode] = cartItem # Add to the dictionary
- def showAll(self):
- print("Item(s) in the shopping cart:")
- for cItem in self._items.values():
- print(cItem)
- def remove(self, pCode):
- if pCode in self._items.keys():
- del self._items[pCode] # Remove from collection
- def search(self, pCode):
- if pCode in self._items.keys():
- return self._items[pCode]
- else:
- return None # As stated in the question
- def getTotal(self):
- totalAmt = 0
- for eachItem in self._items.values():
- totalAmt += eachItem.cost # Add up each cartItem
- return totalAmt
- ######################
- def main():
- # Quick test
- p1 = Product('p1', 'desc 1', 10)
- p2 = Product('p2', 'desc 2', 20)
- c1 = CartItem(p1, 10) # 10 units of Product: p1
- c2 = CartItem(p2, 20) # 20 units of Product: p2
- sCart = ShoppingCart("John") # One instance of ShoppingCart
- sCart.add(c1) # c1 go into the shopping cart
- sCart.add(c2) # Add another item into the shopping cart
- sCart.showAll() # Print items in the shopping cart
- # Next, remove cartItem from the shopping cart
- sCart.remove('p1') # Remove product 'p1' from the shopping cart
- sCart.showAll() # Check again to see if the item is removed
- # Next, search method
- cItem = sCart.search('p2') # Look for cartItem containing Product: 'p2'
- if cItem is None:
- print("Not in the shopping cart")
- else:
- print(cItem)
- cItem = sCart.search('p3') # Look for cartItem containing Product: 'p3'
- if cItem is None:
- print("Not in the shopping cart")
- else:
- print(cItem)
- # Last method, get the total cost
- total = sCart.getTotal()
- print(f"Total is ${total}")
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement