Python  购物车

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.

         

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容