模拟购物车购物过程python,python 学习,使用类模拟购物车代码

这个博客展示了如何用Python创建一个简单的购物车类`ShoppingCart`。类中包含`add_item`方法用于添加商品和价格,`remove_item`方法用于移除商品。实例化购物车并添加商品'apple'到购物车。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

class ShoppingCart(object):

"""Creates shopping cart 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."

my_cart=ShoppingCart("wangweiwei")

my_cart.add_item("apple",12)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值