假设我们有一个商品类'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

以上代码演示了如何创建商品对象,创建购物车对象,并将商品添加到购物车中,最后打印购物车中的商品和总金额。

Python代码实现购物车的添加功能