Advertisement
Lyuben_Andreev

MultipleInheritancePolymorphism

Aug 18th, 2024
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 7.62 KB | Source Code | 0 0
  1. import math
  2. import json
  3.  
  4. class Shape:
  5.     def area(self):
  6.         # Таск 1: Дефиниране на метод за изчисляване на площ за базовия клас Shape
  7.         raise NotImplementedError("Subclasses must implement the area method")
  8.  
  9.     # Таск 3: Записване на формата във файл в JSON формат
  10.     def save(self, filename):
  11.         with open(filename, 'a') as file:
  12.             file.write(f"{json.dumps(self.to_dict())}\n")
  13.  
  14.     # Таск 3: Зареждане на форми от файл
  15.     @classmethod
  16.     def load(cls, filename):
  17.         shapes = []
  18.         with open(filename, 'r') as file:
  19.             for line in file:
  20.                 shape_info = line.strip()
  21.                 if not shape_info:
  22.                     continue
  23.  
  24.                 try:
  25.                     # Декодиране на JSON данните и създаване на обекти от тях
  26.                     shape_data = json.loads(shape_info)
  27.                     shape_type = shape_data.get('type')
  28.                     attributes = shape_data.get('attributes', {})
  29.  
  30.                     if shape_type == 'Square':
  31.                         shape = Square(attributes['x'], attributes['y'], attributes['side_length'])
  32.                     elif shape_type == 'Rectangle':
  33.                         shape = Rectangle(attributes['x'], attributes['y'], attributes['width'], attributes['height'])
  34.                     elif shape_type == 'Circle':
  35.                         shape = Circle(attributes['x'], attributes['y'], attributes['radius'])
  36.                     elif shape_type == 'Ellipse':
  37.                         shape = Ellipse(attributes['x'], attributes['y'], attributes['width'], attributes['height'])
  38.                     else:
  39.                         print(f"Unrecognized shape type: {shape_type}")
  40.                         continue
  41.  
  42.                     shapes.append(shape)
  43.                 except json.JSONDecodeError:
  44.                     print(f"Error decoding JSON: {shape_info}")
  45.                 except KeyError as e:
  46.                     # Отчет за липсващ атрибут в данните
  47.                     print(f"Missing attribute in shape data: {e}")
  48.  
  49.         return shapes
  50.  
  51.     def to_dict(self):
  52.         # Таск 3: Методът to_dict() за сериализиране на обектите в JSON формат
  53.         raise NotImplementedError("Subclasses must implement the to_dict method")
  54.  
  55.     def show(self):
  56.         # Таск 3: Показване на информация за формата
  57.         print(f"Shape info: {self}")
  58.  
  59.     def __str__(self):
  60.         return self.show()
  61.  
  62. class Rectangle(Shape):
  63.     def __init__(self, x, y, width, height):
  64.         self.x = x
  65.         self.y = y
  66.         self.width = width
  67.         self.height = height
  68.  
  69.     def area(self):
  70.         # Таск 1: Изчисляване на площта на правоъгълника
  71.         return self.width * self.height
  72.  
  73.     def to_dict(self):
  74.         # Таск 3: Сериализиране на правоъгълника в JSON формат
  75.         return {
  76.             "type": "Rectangle",
  77.             "attributes": {
  78.                 "x": self.x,
  79.                 "y": self.y,
  80.                 "width": self.width,
  81.                 "height": self.height
  82.             }
  83.         }
  84.  
  85.     def __int__(self):
  86.         # Таск 2: Преобразуване на обекта в цяло число (площта на правоъгълника)
  87.         return int(self.area())
  88.  
  89.     def __str__(self):
  90.         # Таск 2: Връщане на информация за правоъгълника
  91.         return f"Rectangle at ({self.x}, {self.y}) with width {self.width} and height {self.height}"
  92.  
  93. class Circle(Shape):
  94.     def __init__(self, x, y, radius):
  95.         self.x = x
  96.         self.y = y
  97.         self.radius = radius
  98.  
  99.     def area(self):
  100.         # Таск 1: Изчисляване на площта на кръга
  101.         return math.pi * (self.radius ** 2)
  102.  
  103.     def to_dict(self):
  104.         # Таск 3: Сериализиране на кръга в JSON формат
  105.         return {
  106.             "type": "Circle",
  107.             "attributes": {
  108.                 "x": self.x,
  109.                 "y": self.y,
  110.                 "radius": self.radius
  111.             }
  112.         }
  113.  
  114.     def __int__(self):
  115.         # Таск 2: Преобразуване на обекта в цяло число (площта на кръга)
  116.         return int(self.area())
  117.  
  118.     def __str__(self):
  119.         # Таск 2: Връщане на информация за кръга
  120.         return f"Circle at ({self.x}, {self.y}) with radius {self.radius}"
  121.  
  122. class Square(Shape):
  123.     def __init__(self, x, y, side_length):
  124.         self.x = x
  125.         self.y = y
  126.         self.side_length = side_length
  127.  
  128.     def area(self):
  129.         # Таск 1: Изчисляване на площта на квадрата
  130.         return self.side_length ** 2
  131.  
  132.     def to_dict(self):
  133.         # Таск 3: Сериализиране на квадрата в JSON формат
  134.         return {
  135.             "type": "Square",
  136.             "attributes": {
  137.                 "x": self.x,
  138.                 "y": self.y,
  139.                 "side_length": self.side_length
  140.             }
  141.         }
  142.  
  143.     def __int__(self):
  144.         # Таск 2: Преобразуване на обекта в цяло число (площта на квадрата)
  145.         return int(self.area())
  146.  
  147.     def __str__(self):
  148.         # Таск 2: Връщане на информация за квадрата
  149.         return f"Square at ({self.x}, {self.y}) with side length {self.side_length}"
  150.  
  151. class Ellipse(Shape):
  152.     def __init__(self, x, y, width, height):
  153.         self.x = x
  154.         self.y = y
  155.         self.width = width
  156.         self.height = height
  157.  
  158.     def area(self):
  159.         # Таск 1: Изчисляване на площта на елипсата
  160.         return math.pi * (self.width / 2) * (self.height / 2)
  161.  
  162.     def to_dict(self):
  163.         # Таск 3: Сериализиране на елипсата в JSON формат
  164.         return {
  165.             "type": "Ellipse",
  166.             "attributes": {
  167.                 "x": self.x,
  168.                 "y": self.y,
  169.                 "width": self.width,
  170.                 "height": self.height
  171.             }
  172.         }
  173.  
  174.     def __int__(self):
  175.         # Таск 2: Преобразуване на обекта в цяло число (площта на елипсата)
  176.         return int(self.area())
  177.  
  178.     def __str__(self):
  179.         # Таск 2: Връщане на информация за елипсата
  180.         return f"Ellipse at ({self.x}, {self.y}) with width {self.width} and height {self.height}"
  181.  
  182. # Основна функция за демонстриране на функционалността
  183. def main():
  184.     shapes = [
  185.         Square(0, 0, 10),
  186.         Rectangle(1, 1, 5, 10),
  187.         Circle(2, 2, 7),
  188.         Ellipse(3, 3, 10, 5)
  189.     ]
  190.  
  191.     # Таск 3: Запис на формите във файл
  192.     filename = 'shapes.txt'
  193.     with open(filename, 'w') as file:
  194.         for shape in shapes:
  195.             shape.save(filename)
  196.  
  197.     # Таск 3: Зареждане на формите от файла
  198.     loaded_shapes = Shape.load(filename)
  199.  
  200.     # Принтиране на информация за всяка заредена форма
  201.     for shape in loaded_shapes:
  202.         print(f"Loaded shape: {shape}")
  203.         print(f"Area: {shape.area()}")
  204.  
  205. # Извикване на основната функция
  206. main()
  207.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement