Python uses classes to simulate an online shopping cart, supporting operations such as adding and removing products

Document 对象参考手册Python3 Examples

We will use Python classes to simulate an online shopping cart. The cart will support functions such as adding products, removing products, viewing cart contents, and calculating the total price.

Example

class ShoppingCart:
    def __init__(self):
        self.items = []

    def add_item(self, name, price, quantity=1):
        self.items.append({'name': name, 'price': price, 'quantity': quantity})

    def remove_item(self, name):
        self.items = [item for item in self.items if item['name'] != name]

    def view_cart(self):
        if not self.items:
            print("Your shopping cart is empty.")
        else:
            for item in self.items:
                print(f"{item['name']} - ${item['price']} x {item['quantity']}")

    def calculate_total(self):
        return sum(item['price'] * item['quantity'] for item in self.items)

# Example usage
cart = ShoppingCart()
cart.add_item("Apple", 0.5, 3)
cart.add_item("Banana", 0.3, 5)
cart.view_cart()
print(f"Total: ${cart.calculate_total()}")
cart.remove_item("Banana")
cart.view_cart()
print(f"Total: ${cart.calculate_total()}")

Code analysis:

  1. __init__The method initializes the shopping cart and creates an empty listitemsto store products.
  2. add_itemThe method is used to add products to the shopping cart. It accepts the product name, price, and quantity (default is 1) as parameters, and adds them to theitemslist.
  3. remove_itemThe method is used to remove products with a specified name from the shopping cart, using list comprehensions to filter out unwanted products.
  4. view_cartThe method is used to view the products in the shopping cart. If the cart is empty, it prompts that the cart is empty; otherwise, it iterates over theitemslist and prints detailed information about each product.
  5. calculate_totalThe method is used to calculate the total price of all products in the shopping cart, using list comprehensions and thesumfunction.

Output result:

Apple - $0.5 x 3
Banana - $0.3 x 5
Total: $2.4
Apple - $0.5 x 3
Total: $1.5

Document 对象参考手册Python3 Examples

Other extensions