Question
How do I create an instance of ShoppingCart called my_cart?
Answer
To create your own instance of ShoppingCart
, you do not need to add any code inside of the existing class ShoppingCart
code block. Rather, we need to add to the end of the program, completely unindented, the new object and then use that object.
We create an object like this:
my_object = ClassName("parameters")
Then we use an object’s method like this:
my_object.method_name("parameters")
2 Likes
so my question is, when I put my name in for customer_name, how does this ever get used, I cannot figure out how to print or how it ties into my_cart, why would i just not set my name to cart and forget about my_cart
class ShoppingCart(object):
items_in_cart = {}
def __init__(self, customer_name):
self.customer_name = customer_name
def add_item(self, product, price):
if not product in self.items_in_cart:
self.items_in_cart[product] = price
print product + " added."
else:
print product + " is already in the cart."
def remove_item(self, product):
if product in self.items_in_cart:
del self.items_in_cart[product]
print product + " removed."
else:
print product + " is not in the cart."
my_cart = ShoppingCart("Jason's")
my_cart.add_item("coke", 3.15)
my_cart.add_item("pepsi", 3.16)
my_cart.add_item("vanilla", 3.17)
print ShoppingCart.items_in_cart
my_cart.remove_item("coke")
print ShoppingCart.items_in_cart
1 Like
at the moment customer_name
doesn’t get used
you can print the name:
print my_cart.customer_name
you could also make a method which prints something like: Jason’s has the following items in his cart: coke, pepsi, vanilla.
1 Like