[Tutor] Help with this work

Alan Gauld alan.gauld at yahoo.co.uk
Tue Feb 7 05:13:33 EST 2017


On 07/02/17 04:08, Sasiliyu Adetunji wrote:
> I have been working on yhis assignment

You are asking for help but in what regard?
There is no question or problem statement in your post?

I've put some general comments below...

> class ShoppingCart(object):
> 
>   def __init__(self):
>     self.total = 0
>     self.items = {}
> 
>   def add_item(self, item_name, quantity, price):
>     if not item_name in self.items:
>       self.items[item_name] = quantity
>     else:
>       self.items[item_name] += quantity

This is often better done using the get()
or setdefault() methods of the dictionary.
For example:

self.items[item_name] = self.items.get(item_name,0)) + quantity

>     self.total += quantity * price
> 
>   def remove_item(self, item_name, quantity, price):
>     if quantity > self.items[item_name]:
>       self.items[item_name] = quantity
>     else:
>       self.items[item_name] -= quantity
>     self.total -= quantity * price

I'm pretty sure the first part of the if statement is wrong.
Read the specification again.

Also there is a more subtle problem with your last line
if quantity is greater than the stored self.items count.
Try working through it manually with some before/after
figures and see if the results are what you would expect.

>   def checkout(self, cash_paid):
>     self.cash_paid = cash_paid
>     if cash_paid < self.total:
>       return "Cash paid not enough"
>     else:
>       return cash_paid - self.total

This meets the specification but I hate the design
here. But that's not your fault....

> class Shop(ShoppingCart):
>   def __init__(self):
>     self.quantity = 100
> 
>   def remove_item(self):
>     self.quantity -= 1
> 

It says override the remove_item.
But shopping carts remove_item takes 3 parameters
so your new version should take the same three
parameters. It should probably call the superclass's
remove_item too. However I agree that you have done
what the spec asked for, I just suspect the spec
is badly written for this particular case...

> Kindly assist me

In what way? You haven't said what the issue is.


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list