fork download
  1. class product:
  2. def __init__(self, ID: str, name: str, price: int, man_name: str) -> None:
  3. self.id = ID
  4. self.name = name
  5. self.price = price
  6. self.man_name = man_name
  7.  
  8. # get the string representation of the product
  9. def __str__(self) -> str:
  10. return "Product ID:\t\t" + self.id + "\nProduct Name:\t\t" + \
  11. self.name + "\nProduct Price:\t\t" + str(self.price) + \
  12. "\nManufacturer Name:\t" + self.man_name
  13.  
  14. # compare if the two products are the same
  15. def __eq__(self, b) -> bool:
  16. if self.id == b.id and self.name == b.name and \
  17. self.price == b.price and self.man_name == b.man_name:
  18. return True
  19. return False
  20.  
  21. # the same way ne method
  22. def __ne__(self, b) -> bool:
  23. if self.id != b.id or self.name != b.name or \
  24. self.price != b.price or self.man_name != b.man_name:
  25. return True
  26. return False
  27.  
  28. # we override the __hash__ magic method which is useful in sets
  29. # if two elements have same hash they are equal
  30. def __hash__(self):
  31. return hash(self.id)
  32.  
  33. # get the id of the product
  34. def getID(self):
  35. return self.id
  36.  
  37. # get the name of the product
  38. def getName(self):
  39. return self.name
  40.  
  41. # get the price of the product
  42. def getPrice(self):
  43. return self.price
  44.  
  45. # get the manufacturer name
  46. def getManufacturerName(self):
  47. return self.man_name
  48.  
  49. if __name__ == '__main__':
  50. prodList = [
  51. product('d', 'e', 2, 'f'),
  52. product('a', 'b', 1, 'c'),
  53. product('m', 'n', 5, 'o'),
  54. product('p', 'q', 6, 'r'),
  55. product('j', 'k', 4, 'l'),
  56. product('s', 't', 7, 'u'),
  57. product('g', 'h', 3, 'i'),
  58. product('v', 'w', 8, 'x'),
  59. ]
  60.  
  61. pricesort = sorted(prodList, key = lambda a: a.price)
  62. # for prod in pricesort:
  63. # print(prod)
  64. # print("==========================")
  65.  
  66. # print("-----------------------------------------------------")
  67. # revpricesort = sorted(prodList, key = lambda a: a.price)[::-1]
  68. # for prod in revpricesort:
  69. # print(prod)
  70. # print("==========================")
  71.  
  72. prodListB = [
  73. product('a', 'b', 8, 'c'),
  74. product('m', 'n', 56, 'o'),
  75. product('aa', 'bb', 45, 'c'),
  76. product('bb', 'ds', 65, 'o'),
  77. product('zz', 'vv', 71, 'c'),
  78. product('ff', 'df', 59, 'o'),
  79. ]
  80.  
  81. # implement the append part
  82.  
  83. # implement the slicing part
  84.  
  85. prodList.extend(prodListB)
  86. print(hash(prodList[1]) == hash(prodListB[0]))
  87. print(len(set([prodList[1], prodListB[0]])))
  88.  
Success #stdin #stdout 0.02s 9056KB
stdin
Standard input is empty
stdout
True
2