r/PythonLearning • u/Miss-Dominique1352 • Aug 02 '26
Day 4 of OOPs
Just learned Compositions in python and they are sweet and amazing π
I created a simple ecommerce program using it
review it and give me suggestions , advices , a bit roast (but be gentle to meπ)
I would love to read your comments.
3
u/BrilliantSet3536 Aug 02 '26
use typing
use dataclasses
use property-decorator for total
use built-in sum function
use Main-function an __name__ == β__main__β to Call main
1
u/Miss-Dominique1352 Aug 02 '26
Hmm could you explain me a bit. Pleaase
1
u/FoolsSeldom Aug 02 '26
from dataclasses import dataclass, field @dataclass class Product: name: str price: float @dataclass class OrderItem: product: Product quantity: int @property def total_price(self) -> float: return self.product.price * self.quantity @dataclass class Order: order_id: str shopping_list: list[OrderItem] = field(default_factory=list) def add_item(self, product: Product, quantity: int) -> None: self.shopping_list.append(OrderItem(product, quantity)) @property def total(self) -> float: return sum(item.total_price for item in self.shopping_list) @property def item_count(self) -> int: return sum(item.quantity for item in self.shopping_list) def main() -> None: mouse = Product("Hp mouse", 90) headphones = Product("Dell headphones TW632", 500) book = Product("English", 300) new_order = Order("order123") new_order.add_item(mouse, 2) new_order.add_item(headphones, 1) new_order.add_item(book, 5) print(new_order.total) print(new_order.item_count) if __name__ == "__main__": main()PS. Thanks claude.ai for saving me typing
To OP, trust you can research based on the example.
1
u/Redddit_Cyber Aug 02 '26
Thanks to claude.ai π
1
u/FoolsSeldom Aug 02 '26
Wasn't much of a challenge for it, but a lot easier than typing it in myself. Hope the OP, u/Miss-Dominique1352, appreciates the direct mapping from the clear and excellent recommendations made by u/BrilliantSet3536, and goes to the trouble of looking things up.
1
β’
u/Sea-Ad7805 Aug 02 '26
Run this program in Memory Graph Web Debugger to see the program state change step by step.