fork download
  1. #
  2. # Operator Overloading
  3. #
  4. class Quantity:
  5.  
  6. def __init__(self, value):
  7. self.value = value
  8.  
  9. def __add__(self, other):
  10. new_value = self.value + other.value
  11. return Quantity(new_value)
  12.  
  13. def __sub__(self, other):
  14. new_value = self.value - other.value
  15. return Quantity(new_value)
  16.  
  17. def __mul__(self, other):
  18. new_value = self.value * other.value
  19. return Quantity(new_value)
  20.  
  21. def __str__(self):
  22. return "Quantity["+ str(self.value) +"]"
  23.  
  24. def __eq__(self, other):
  25. return self.value == other.value
  26.  
  27. def __gt__(self, other):
  28. return self.value > other.value
  29.  
  30. def __ge__(self, other):
  31. return self.value >= other.value
  32.  
  33. def __lt__(self, other):
  34. return self.value < other.value
  35.  
  36. def __le__(self, other):
  37. return self.value <= other.value
  38. def main():
  39. q1 = Quantity(10)
  40. q2 = Quantity(20)
  41. q3 = q1 + q2
  42. print(q3)
  43. print(q1<q2)
  44. main()
Success #stdin #stdout 0.02s 9264KB
stdin
Standard input is empty
stdout
Quantity[30]
True