如何使用类编写简易模拟代码:实现条码添加商品及总价统计
Solution: Simple Product Manager Class
Got it, let's build a clean, reusable class that checks all your boxes. First, a quick note: your initial barcode syntax was a bit off (it should be a dictionary, not a list with key-value pairs). We'll adjust that to map barcodes to product names, plus add a price mapping since we need to track individual product costs.
Here's the implementation:
class ProductManager: def __init__(self): # Initialize the required tracking lists self.product_list = [] self.price = [] # Barcode to product name mapping (fixed your initial syntax) self.barcode_to_product = {123: "banana", 234: "apple", 345: "orange", 456: "pear"} # Product name to price mapping (customize these values as needed) self.product_to_price = {"banana": 1.99, "apple": 1.49, "orange": 0.99, "pear": 2.49} def add_product(self, input_barcode): # Check if the entered barcode exists in our system if input_barcode in self.barcode_to_product: product_name = self.barcode_to_product[input_barcode] # Add the product and its price to the respective lists self.product_list.append(product_name) self.price.append(self.product_to_price[product_name]) print(f"Successfully added {product_name} to your list!") else: print(f"Oops, barcode {input_barcode} isn't recognized. Try another one.") def get_total_price(self): # Calculate and return the sum of all added product prices total = sum(self.price) print(f"Total cost of your selected products: ${total:.2f}") return total
How to use this class:
- Create an instance of
ProductManager - Call
add_product()with a barcode number to add items - Use
get_total_price()to compute the sum of all added products
Example walkthrough:
# Set up the product manager shopping_manager = ProductManager() # Add items using their barcodes shopping_manager.add_product(123) # Adds banana shopping_manager.add_product(456) # Adds pear shopping_manager.add_product(234) # Adds apple # Calculate the total shopping_manager.get_total_price() # Output: Total cost of your selected products: $5.97 # Check the tracked lists print(shopping_manager.product_list) # Output: ['banana', 'pear', 'apple'] print(shopping_manager.price) # Output: [1.99, 2.49, 1.49]
Quick breakdown of key parts:
- Initialization: We set up the two tracking lists, plus two dictionaries to keep barcode-to-product and product-to-price mappings organized (easy to update if you add new products later).
- Adding products: The
add_productmethod validates the input barcode, finds the matching product, and updates both lists only if the barcode is valid. - Total calculation: The
get_total_pricemethod uses Python's built-insum()function for efficiency, and formats the result to 2 decimal places for readability.
You can easily extend this class—like adding a method to remove items, clear the lists, or display all selected products—if you need more functionality later.
内容的提问来源于stack exchange,提问作者M. Dobariya
相关产品推荐
相关产品推荐

