3-tier.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. class Data(object):
  4. """ Data Store Class """
  5. products = {
  6. 'milk': {'price': 1.50, 'quantity': 10},
  7. 'eggs': {'price': 0.20, 'quantity': 100},
  8. 'cheese': {'price': 2.00, 'quantity': 10}
  9. }
  10. def __get__(self, obj, klas):
  11. print ("(Fetching from Data Store)")
  12. return {'products': self.products}
  13. class BusinessLogic(object):
  14. """ Business logic holding data store instances """
  15. data = Data()
  16. def product_list(self):
  17. return self.data['products'].keys()
  18. def product_information(self, product):
  19. return self.data['products'].get(product, None)
  20. class Ui(object):
  21. """ UI interaction class """
  22. def __init__(self):
  23. self.business_logic = BusinessLogic()
  24. def get_product_list(self):
  25. print('PRODUCT LIST:')
  26. for product in self.business_logic.product_list():
  27. print(product)
  28. print('')
  29. def get_product_information(self, product):
  30. product_info = self.business_logic.product_information(product)
  31. if product_info:
  32. print('PRODUCT INFORMATION:')
  33. print('Name: {0}, Price: {1:.2f}, Quantity: {2:}'.format(
  34. product.title(), product_info.get('price', 0),
  35. product_info.get('quantity', 0)))
  36. else:
  37. print('That product "{0}" does not exist in the records'.format(
  38. product))
  39. def main():
  40. ui = Ui()
  41. ui.get_product_list()
  42. ui.get_product_information('cheese')
  43. ui.get_product_information('eggs')
  44. ui.get_product_information('milk')
  45. ui.get_product_information('arepas')
  46. if __name__ == '__main__':
  47. main()
  48. ### OUTPUT ###
  49. # PRODUCT LIST:
  50. # (Fetching from Data Store)
  51. # cheese
  52. # eggs
  53. # milk
  54. #
  55. # (Fetching from Data Store)
  56. # PRODUCT INFORMATION:
  57. # Name: Cheese, Price: 2.00, Quantity: 10
  58. # (Fetching from Data Store)
  59. # PRODUCT INFORMATION:
  60. # Name: Eggs, Price: 0.20, Quantity: 100
  61. # (Fetching from Data Store)
  62. # PRODUCT INFORMATION:
  63. # Name: Milk, Price: 1.50, Quantity: 10
  64. # (Fetching from Data Store)
  65. # That product "arepas" does not exist in the records