fork download
  1. class Product:
  2. def __init__(self, name, price):
  3. self.name = name
  4. self.price = price
  5.  
  6. def __repr__(self):
  7. return f"Product(name='{self.name}', price={self.price})"
  8.  
  9. def __lt__(self, other):
  10. # Define comparison based on price
  11. return self.price < other.price
  12.  
  13. products = [
  14. Product("Laptop", 1200),
  15. Product("Mouse", 25),
  16. Product("Keyboard", 75),
  17. Product("Monitor", 300)
  18. ]
  19.  
  20. # Sort directly using the defined __lt__ method
  21. sorted_products = sorted(products)
  22. print(f"Sorted products: {sorted_products}")
Success #stdin #stdout 0.1s 14080KB
stdin
Standard input is empty
stdout
Sorted products: [Product(name='Mouse', price=25), Product(name='Keyboard', price=75), Product(name='Monitor', price=300), Product(name='Laptop', price=1200)]