说明
《Python 教程》 持续更新中,提供建议、纠错、催更等加作者微信: gairuo123(备注:pandas教程)和关注公众号「盖若」ID: gairuo。跟作者学习,请进入 Python学习课程。欢迎关注作者出版的书籍:《深入浅出Pandas》 和 《Python之光》。
(编码题)用 Python 设计一个购物车功能,实现以下功能:
并对设计代码进行测试。
Python 代码如下
class Item:
def __init__(self, name: str, price: float):
self.name = name
self.price = price
class ShoppingCart:
def __init__(self):
self.cart = {}
def add_item(self, item: Item, quantity: int = 1) -> None:
"""
Add items to the shopping cart.
Args:
- item (Item): The item to be added.
- quantity (int): The quantity of the item. Default is 1.
Returns:
- None
"""
self.cart[item.name] = {"price": item.price, "quantity": self.cart.get(item.name, {}).get("quantity", 0) + quantity}
def remove_item(self, item: Item, quantity: int = 1) -> None:
"""
Remove items from the shopping cart.
Args:
- item (Item): The item to be removed.
- quantity (int): The quantity of the item to be removed. Default is 1.
Returns:
- None
"""
if item.name in self.cart:
self.cart[item.name]["quantity"] = max(0, self.cart[item.name]["quantity"] - quantity)
if self.cart[item.name]["quantity"] == 0:
del self.cart[item.name]
def calculate_total(self) -> float:
"""
Calculate the total cost of items in the shopping cart.
Returns:
- float: The total cost.
"""
return sum(item["price"] * item["quantity"] for item in self.cart.values())
def clear_cart(self) -> None:
"""
Clear all items from the shopping cart.
Returns:
- None
"""
self.cart = {}
def checkout(self) -> None:
"""
Simulate the checkout process.
Returns:
- None
"""
total_cost = self.calculate_total()
print(f"Total cost of items in the cart: ${total_cost:.2f}")
confirmation = input("Confirm purchase? (yes/no): ").lower()
if confirmation == "yes":
print("Payment successful! Thank you for your purchase.")
self.clear_cart()
else:
print("Purchase canceled.")
def __str__(self) -> str:
"""
Return a string representation of the shopping cart.
Returns:
- str: String representation of the shopping cart data.
"""
return str(self.cart)
# Example usage:
laptop = Item(name="Laptop", price=800.0)
mouse = Item(name="Mouse", price=20.0)
monitor = Item(name="Monitor", price=300.0)
cart = ShoppingCart()
cart.add_item(item=laptop, quantity=2)
cart.add_item(item=mouse, quantity=5)
cart.add_item(item=monitor, quantity=1)
print("Cart data before checkout:", cart)
print('Cart total:', cart.calculate_total())
cart.checkout()
# Verify the cart is cleared after checkout
print("Cart data after checkout:", cart)
查看相关链接中的知识。
(完)
更新时间:2024-08-16 22:50:33 标签:python 习题 类 购物车