123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111 |
- '''
- Вычисляемые свойства
- Если вам нужен атрибут, который будет вычислять
- свое значение каждый раз динамически при доступе к нему, то property — это то, что вам нужно. Такие атрибуты обычно называются вычисляемыми атрибутами.
- '''
- import time
- class Square:
- def __init__(self, s):
- self.__side = s
- self.__area = None
- @property
- def side(self):
- return self.__side
-
- @side.setter
- def side(self, value):
- self.side = value
- self.__area = None
- @property
- def area(self):
- if self.__area is None:
- print('Calculate area...')
- time.sleep(0.5)
- self.__area = self.side ** 2
- return self.__area
- def test_1():
- sq = Square(4)
- print(sq.area)
- print(sq.area)
- #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
- class Colour:
- def __init__(self, colour):
- self.colour = colour
- @property
- def red(self):
- return int(self.colour[1:3], base=16)
- @property
- def green(self):
- return int(self.colour[3:5], base=16)
- @property
- def blue(self):
- return int(self.colour[5:7], base=16)
- def test_2():
- colour = Colour("#aacce4")
- print(colour.red)
- print(colour.green)
- print(colour.blue)
- #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
- class Ingredient:
- def __init__(self, name, weight, price):
- self.name = name
- self.weight = weight
- self.price = price # стоимость за 100гр
- @property
- def cost(self):
- return self.weight * self.price/100
- class Pizza:
- def __init__(self, name, ingredients=None):
- self.name = name
- if ingredients is None:
- self.ingredients = []
- else:
- self.ingredients = ingredients
- @property
- def cost(self):
- s = 0
- for x in self.ingredients:
- s += x.cost
- return s + 100
- def test_3():
- chicken = Ingredient('chicken', 200, 80)
- mozzarella = Ingredient('mozzarella', 300, 110)
- sauce_bbq = Ingredient('sauce bbq', 150, 70)
- red_onion = Ingredient('red onion', 150, 50)
- print('Цена курицы', chicken.cost)
- print('Цена моцарелы', mozzarella.cost)
- print('Цена соуса', sauce_bbq.cost)
- print('Цена красного лука', red_onion.cost)
- barbecue = Pizza('BBQ', [chicken, mozzarella, sauce_bbq, red_onion])
- print('Стоимость пиццы BBQ', barbecue.cost)
- def main():
- # test_1()
- # test_2()
- test_3()
- if __name__ == '__main__':
- main()
|