class ShoppingCart(object):
""" creates shoppingcart objects for users of our fine website."""
items_in_cart = {}
def __init__(self,customer_name):
self.customer_name = customer_name
def add_item(self,product,price):
"""Add product to the cart."""
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):
""" Remove product from the cart."""
if product in self.items_in_cart:
del self.items_in_cart[product]
print product + "removed."
else:
print product +"is not in the cart."
在阿里的淘宝,腾讯的京东有这个程序的影子
create an instance of ShoppingCart called my-cart.initialize it with any values you like.then use the add_item method to add an item to your cart.
hint:
since the ShoppingCart class has an __init__() method that takes a customer name.I'd create my_cart like so:
my_cart = ShoppingCart("Eric")
calling the add_item() method might then be:
my_cart.add_item("ukelele",10)
ShoppingCart s,c 要大写,小写就出错
"self.items_in_cart[product] = price"
当您将直赋值到未在字典中的键时,该键将被添加指定值。
when you assign a value to a key that is not already in the dictionary this key is added with the assigned value.