写一段加入购物车的代码
假设我们有一个商品类Product,其中包含商品的名称name和价格price属性。我们还有一个购物车类ShoppingCart,其中包含购物车中的商品列表products和购物车的总金额total属性。
class Product:
def __init__(self, name, price):
self.name = name
self.price = price
class ShoppingCart:
def __init__(self):
self.products = []
self.total = 0
def add_to_cart(self, product):
self.products.append(product)
self.total += product.price
# 创建商品对象
product1 = Product("手机", 999)
product2 = Product("电视", 1999)
# 创建购物车对象
cart = ShoppingCart()
# 将商品添加到购物车
cart.add_to_cart(product1)
cart.add_to_cart(product2)
# 打印购物车中的商品和总金额
print("购物车中的商品:")
for product in cart.products:
print(product.name, product.price)
print("购物车总金额:", cart.total)
运行以上代码,将会输出以下结果:
购物车中的商品:
手机 999
电视 1999
购物车总金额: 2998
以上代码演示了如何创建商品对象,创建购物车对象,并将商品添加到购物车中,最后打印购物车中的商品和总金额
原文地址: https://www.cveoy.top/t/topic/iHJn 著作权归作者所有。请勿转载和采集!