property_1.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. '''
  2. Вычисляемые свойства
  3. Если вам нужен атрибут, который будет вычислять
  4. свое значение каждый раз динамически при доступе к нему, то property — это то, что вам нужно. Такие атрибуты обычно называются вычисляемыми атрибутами.
  5. '''
  6. import time
  7. class Square:
  8. def __init__(self, s):
  9. self.__side = s
  10. self.__area = None
  11. @property
  12. def side(self):
  13. return self.__side
  14. @side.setter
  15. def side(self, value):
  16. self.side = value
  17. self.__area = None
  18. @property
  19. def area(self):
  20. if self.__area is None:
  21. print('Calculate area...')
  22. time.sleep(0.5)
  23. self.__area = self.side ** 2
  24. return self.__area
  25. def test_1():
  26. sq = Square(4)
  27. print(sq.area)
  28. print(sq.area)
  29. #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  30. class Colour:
  31. def __init__(self, colour):
  32. self.colour = colour
  33. @property
  34. def red(self):
  35. return int(self.colour[1:3], base=16)
  36. @property
  37. def green(self):
  38. return int(self.colour[3:5], base=16)
  39. @property
  40. def blue(self):
  41. return int(self.colour[5:7], base=16)
  42. def test_2():
  43. colour = Colour("#aacce4")
  44. print(colour.red)
  45. print(colour.green)
  46. print(colour.blue)
  47. #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  48. class Ingredient:
  49. def __init__(self, name, weight, price):
  50. self.name = name
  51. self.weight = weight
  52. self.price = price # стоимость за 100гр
  53. @property
  54. def cost(self):
  55. return self.weight * self.price/100
  56. class Pizza:
  57. def __init__(self, name, ingredients=None):
  58. self.name = name
  59. if ingredients is None:
  60. self.ingredients = []
  61. else:
  62. self.ingredients = ingredients
  63. @property
  64. def cost(self):
  65. s = 0
  66. for x in self.ingredients:
  67. s += x.cost
  68. return s + 100
  69. def test_3():
  70. chicken = Ingredient('chicken', 200, 80)
  71. mozzarella = Ingredient('mozzarella', 300, 110)
  72. sauce_bbq = Ingredient('sauce bbq', 150, 70)
  73. red_onion = Ingredient('red onion', 150, 50)
  74. print('Цена курицы', chicken.cost)
  75. print('Цена моцарелы', mozzarella.cost)
  76. print('Цена соуса', sauce_bbq.cost)
  77. print('Цена красного лука', red_onion.cost)
  78. barbecue = Pizza('BBQ', [chicken, mozzarella, sauce_bbq, red_onion])
  79. print('Стоимость пиццы BBQ', barbecue.cost)
  80. def main():
  81. # test_1()
  82. # test_2()
  83. test_3()
  84. if __name__ == '__main__':
  85. main()