delegating.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  1. # Наследование. Делегирование Delegating.
  2. from functools import total_ordering
  3. class Person:
  4. def __init__(self, name, surname) -> None:
  5. self.name = name
  6. self.surname = surname
  7. def __str__(self):
  8. return f"Person {self.name} {self.surname}"
  9. def info(self):
  10. print("Parent class")
  11. print(self)
  12. def breath(self):
  13. print('Человек дышит')
  14. class Doctor(Person):
  15. def __init__(self, name, surname, age):
  16. super().__init__(name, surname)
  17. self.age = age
  18. def __str__(self):
  19. return f"Doctor {self.name} {self.surname}"
  20. def breath(self):
  21. super().breath()
  22. print("Доктор дышит")
  23. class Rectangle:
  24. def __init__(self, length, width):
  25. self.length = length
  26. self.width = width
  27. def area(self):
  28. return self.length * self.width
  29. def perimeter(self):
  30. return 2 * self.length + 2 * self.width
  31. class Square(Rectangle):
  32. def __init__(self, side):
  33. super().__init__(side, side)
  34. class Person:
  35. def __init__(self, name, passport):
  36. self.name = name
  37. self.passport = passport
  38. def display(self):
  39. print(f"{self.name}: {self.passport}")
  40. class Employee(Person):
  41. def __init__(self, name, passport, salary, department):
  42. super().__init__(name, passport)
  43. self.salary = salary
  44. self.department = department
  45. class Vehicle:
  46. def __init__(self, name, mileage, capacity):
  47. self.name = name
  48. self.mileage = mileage
  49. self.capacity = capacity
  50. def fare(self):
  51. return self.capacity * 100
  52. def display(self):
  53. print(f"Total {self.name} fare is: {self.fare()}")
  54. class Bus(Vehicle):
  55. def __init__(self, name, mileage):
  56. super().__init__(name, mileage, 50)
  57. def fare(self):
  58. return super().fare() * 1.1
  59. class Taxi(Vehicle):
  60. def __init__(self, name, mileage):
  61. super().__init__(name, mileage, 4)
  62. def fare(self):
  63. return super().fare() * 1.35
  64. class Transport:
  65. def __init__(self, brand, max_speed, kind=None):
  66. self.brand = brand
  67. self.max_speed = max_speed
  68. self.kind = kind
  69. def __str__(self):
  70. return f"Тип транспорта {self.kind} марки {self.brand} может развить скорость {self.max_speed} км/ч"
  71. class Car(Transport):
  72. def __init__(self, brand, max_speed, mileage, gasoline_residue):
  73. super().__init__(brand, max_speed, kind='Car')
  74. self.mileage = mileage
  75. self.__gasoline_residue = gasoline_residue
  76. @property
  77. def gasoline(self):
  78. return f"Осталось бензина {self.__gasoline_residue} л"
  79. @gasoline.setter
  80. def gasoline(self, value):
  81. if not isinstance(value, int):
  82. print('Ошибка заправки автомобиля')
  83. else:
  84. self.__gasoline_residue += value
  85. print(f"Объем топлива увеличен на {value} л и составляет {self.__gasoline_residue} л")
  86. class Boat(Transport):
  87. def __init__(self, brand, max_speed, owners_name):
  88. super().__init__(brand, max_speed, kind='Boat')
  89. self.owners_name = owners_name
  90. def __str__(self):
  91. return f"Этой лодкой марки {self.brand} владеет {self.owners_name}"
  92. class Plane(Transport):
  93. def __init__(self, brand, max_speed, capacity):
  94. super().__init__(brand, max_speed, kind='Plane')
  95. self.capacity = capacity
  96. def __str__(self):
  97. return f"Самолет марки {self.brand} вмещает в себя {self.capacity} людей"
  98. class Initialization:
  99. def __init__(self, capacity, food: list[str]):
  100. if not isinstance(capacity, int):
  101. print('Количество людей должно быть целым числом')
  102. else:
  103. self.capacity = capacity
  104. self.food = food
  105. class Vegetarian(Initialization):
  106. def __init__(self, capacity, food: list[str]):
  107. super().__init__(capacity, food)
  108. def __str__(self):
  109. return f"{self.capacity} людей предпочитают не есть мясо! Они предпочитают {self.food}"
  110. class MeatEater(Initialization):
  111. def __init__(self, capacity, food: list[str]):
  112. super().__init__(capacity, food)
  113. def __str__(self):
  114. return f"{self.capacity} мясоедов в Москве! Помимо мяса они едят еще и {self.food}"
  115. @total_ordering
  116. class SweetTooth(Initialization):
  117. def __init__(self, capacity, food: list[str]):
  118. super().__init__(capacity, food)
  119. def __str__(self):
  120. return f"Сладкоежек в Москве {self.capacity}. Их самая любимая еда: {self.food}"
  121. def __eq__(self, value):
  122. if isinstance(value, int):
  123. return self.capacity == value
  124. elif isinstance(value, (Initialization)):
  125. return self.capacity == value.capacity
  126. else:
  127. return f"Невозможно сравнить количество сладкоежек с {value}"
  128. def __lt__(self, value):
  129. if isinstance(value, int):
  130. return self.capacity < value
  131. elif isinstance(value, (Initialization)):
  132. return self.capacity < value.capacity
  133. else:
  134. return f"Невозможно сравнить количество сладкоежек с {value}"
  135. def main():
  136. p1 = Initialization('Chuck', [])
  137. assert isinstance(p1, Initialization)
  138. assert not hasattr(p1, 'capacity'), 'Не нужно создавать атрибут "capacity", если передается не целое число'
  139. assert not hasattr(p1, 'food'), 'Не нужно создавать атрибут "food", если передается не целое число'
  140. c1 = Vegetarian(100, [1, 2, 3])
  141. print(c1)
  142. assert isinstance(c1, Vegetarian)
  143. assert c1.capacity == 100
  144. assert c1.food == [1, 2, 3]
  145. b1 = MeatEater(1000, ['Arkasha'])
  146. print(b1)
  147. assert isinstance(b1, MeatEater)
  148. assert b1.capacity == 1000
  149. assert b1.food == ['Arkasha']
  150. pla = SweetTooth(444, [2150, 777])
  151. print(pla)
  152. assert isinstance(pla, SweetTooth)
  153. assert pla.capacity == 444
  154. assert pla.food == [2150, 777]
  155. assert pla > 100
  156. assert not pla < 80
  157. assert not pla == 90
  158. assert pla > c1
  159. assert not pla < c1
  160. assert not pla == c1
  161. assert not pla > b1
  162. assert pla < b1
  163. assert not pla == b1
  164. v_first = Vegetarian(10000, ['Орехи', 'овощи', 'фрукты'])
  165. print(v_first) # 10000 людей предпочитают не есть мясо! Они предпочитают ['Орехи', 'овощи', 'фрукты']
  166. v_second = Vegetarian([23], ['nothing']) # Количество людей должно быть целым числом
  167. m_first = MeatEater(15000, ['Жареную картошку', 'рыба'])
  168. print(m_first) # 15000 мясоедов в Москве! Помимо мяса они едят еще и ['Жареную картошку', 'рыба']
  169. s_first = SweetTooth(30000, ['Мороженое', 'Чипсы', 'ШОКОЛАД'])
  170. print(s_first) # Сладкоежек в Москве 30000. Их самая любимая еда: ['Мороженое', 'Чипсы', 'ШОКОЛАД']
  171. print(s_first > v_first) # Сладкоежек больше, чем людей с другим вкусовым предпочтением
  172. print(30000 == s_first) # Количество сладкоежек из опрошенных людей совпадает с 30000
  173. print(s_first == 25000) # Количество людей не совпадает
  174. print(100000 < s_first) # Количество сладкоежек в Москве не больше, чем 100000
  175. print(100 < s_first) # Количество сладкоежек больше, чем 100
  176. '''
  177. p1 = Transport('Chuck', 50)
  178. print(p1)
  179. assert isinstance(p1, Transport)
  180. assert p1.kind == None
  181. assert p1.brand == 'Chuck'
  182. assert p1.max_speed == 50
  183. assert p1.__dict__ == {'kind': None, 'brand': 'Chuck', 'max_speed': 50}
  184. c1 = Car('RRR', 50, 150, 999)
  185. print(c1)
  186. assert isinstance(c1, Car)
  187. assert c1.kind == "Car"
  188. assert c1.brand == 'RRR'
  189. assert c1.max_speed == 50
  190. assert c1.mileage == 150
  191. assert c1.gasoline == 'Осталось бензина 999 л'
  192. c1.gasoline = 100
  193. assert c1.gasoline == 'Осталось бензина 1099 л'
  194. assert c1.__dict__ == {'kind': 'Car', 'brand': 'RRR', 'max_speed': 50,
  195. 'mileage': 150, '_Car__gasoline_residue': 1099}
  196. b1 = Boat('XXX', 1150, 'Arkasha')
  197. print(b1)
  198. assert isinstance(b1, Boat)
  199. assert b1.kind == "Boat"
  200. assert b1.brand == 'XXX'
  201. assert b1.max_speed == 1150
  202. assert b1.owners_name == 'Arkasha'
  203. pla = Plane('www', 2150, 777)
  204. print(pla)
  205. assert isinstance(pla, Plane)
  206. assert pla.kind == "Plane"
  207. assert pla.brand == 'www'
  208. assert pla.max_speed == 2150
  209. assert pla.capacity == 777
  210. transport = Transport('Telega', 10)
  211. print(transport) # Тип транспорта None марки Telega может развить скорость 10 км/ч
  212. bike = Transport('shkolnik', 20, 'bike')
  213. print(bike) # Тип транспорта bike марки shkolnik может развить скорость 20 км/ч
  214. first_plane = Plane('Virgin Atlantic', 700, 450)
  215. print(first_plane) # Самолет марки Virgin Atlantic может вмещать в себя 450 людей
  216. first_car = Car('BMW', 230, 75000, 300)
  217. print(first_car) # Тип транспорта Car марки BMW может развить скорость 230 км/ч
  218. print(first_car.gasoline) # Осталось бензина на 300 км
  219. first_car.gasoline = 20 # Печатает 'Объем топлива увеличен на 20 л и составляет 320 л'
  220. print(first_car.gasoline) # Осталось бензина на 350 км
  221. second_car = Car('Audi', 230, 70000, 130)
  222. second_car.gasoline = [None] # Печатает 'Ошибка заправки автомобиля'
  223. first_boat = Boat('Yamaha', 40, 'Petr')
  224. print(first_boat) # Этой лодкой марки Yamaha владеет Petr
  225. '''
  226. '''
  227. sc = Vehicle('Scooter', 100, 2)
  228. sc.display()
  229. merc = Bus("Mercedes", 120000)
  230. merc.display()
  231. polo = Taxi("Volkswagen Polo", 15000)
  232. polo.display()
  233. t = Taxi('x', 111)
  234. assert t.__dict__ == {'name': 'x', 'mileage': 111, 'capacity': 4}
  235. t.display()
  236. b = Bus('t', 123)
  237. assert b.__dict__ == {'name': 't', 'mileage': 123, 'capacity': 50}
  238. b.display()
  239. '''
  240. '''
  241. assert issubclass(Employee, Person)
  242. emp = Person("just human", 123456)
  243. emp.display()
  244. assert emp.__dict__ == {'name': 'just human', 'passport': 123456}
  245. emp2 = Employee("Geek2", 534432, 321321, 'Roga & Koputa')
  246. emp2.display()
  247. assert emp2.__dict__ == {'salary': 321321, 'department': 'Roga & Koputa',
  248. 'name': 'Geek2', 'passport': 534432}
  249. '''
  250. '''
  251. rect_1 = Rectangle(3, 2)
  252. assert rect_1.area() == 6
  253. assert rect_1.perimeter() == 10
  254. rect_2 = Rectangle(10, 5)
  255. assert rect_2.area() == 50
  256. assert rect_2.perimeter() == 30
  257. sq_1 = Square(4)
  258. assert sq_1.area() == 16
  259. assert sq_1.perimeter() == 16
  260. sq_2 = Square(10)
  261. assert sq_2.area() == 100
  262. assert sq_2.perimeter() == 40
  263. print('Good')
  264. '''
  265. '''
  266. p = Person('Ivan', 'Ivanov')
  267. d = Doctor('Petr', 'Petrov', 25)
  268. d.info()
  269. '''
  270. if __name__ == '__main__':
  271. main()