Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import math
- import json
- class Shape:
- def area(self):
- # Таск 1: Дефиниране на метод за изчисляване на площ за базовия клас Shape
- raise NotImplementedError("Subclasses must implement the area method")
- # Таск 3: Записване на формата във файл в JSON формат
- def save(self, filename):
- with open(filename, 'a') as file:
- file.write(f"{json.dumps(self.to_dict())}\n")
- # Таск 3: Зареждане на форми от файл
- @classmethod
- def load(cls, filename):
- shapes = []
- with open(filename, 'r') as file:
- for line in file:
- shape_info = line.strip()
- if not shape_info:
- continue
- try:
- # Декодиране на JSON данните и създаване на обекти от тях
- shape_data = json.loads(shape_info)
- shape_type = shape_data.get('type')
- attributes = shape_data.get('attributes', {})
- if shape_type == 'Square':
- shape = Square(attributes['x'], attributes['y'], attributes['side_length'])
- elif shape_type == 'Rectangle':
- shape = Rectangle(attributes['x'], attributes['y'], attributes['width'], attributes['height'])
- elif shape_type == 'Circle':
- shape = Circle(attributes['x'], attributes['y'], attributes['radius'])
- elif shape_type == 'Ellipse':
- shape = Ellipse(attributes['x'], attributes['y'], attributes['width'], attributes['height'])
- else:
- print(f"Unrecognized shape type: {shape_type}")
- continue
- shapes.append(shape)
- except json.JSONDecodeError:
- print(f"Error decoding JSON: {shape_info}")
- except KeyError as e:
- # Отчет за липсващ атрибут в данните
- print(f"Missing attribute in shape data: {e}")
- return shapes
- def to_dict(self):
- # Таск 3: Методът to_dict() за сериализиране на обектите в JSON формат
- raise NotImplementedError("Subclasses must implement the to_dict method")
- def show(self):
- # Таск 3: Показване на информация за формата
- print(f"Shape info: {self}")
- def __str__(self):
- return self.show()
- class Rectangle(Shape):
- def __init__(self, x, y, width, height):
- self.x = x
- self.y = y
- self.width = width
- self.height = height
- def area(self):
- # Таск 1: Изчисляване на площта на правоъгълника
- return self.width * self.height
- def to_dict(self):
- # Таск 3: Сериализиране на правоъгълника в JSON формат
- return {
- "type": "Rectangle",
- "attributes": {
- "x": self.x,
- "y": self.y,
- "width": self.width,
- "height": self.height
- }
- }
- def __int__(self):
- # Таск 2: Преобразуване на обекта в цяло число (площта на правоъгълника)
- return int(self.area())
- def __str__(self):
- # Таск 2: Връщане на информация за правоъгълника
- return f"Rectangle at ({self.x}, {self.y}) with width {self.width} and height {self.height}"
- class Circle(Shape):
- def __init__(self, x, y, radius):
- self.x = x
- self.y = y
- self.radius = radius
- def area(self):
- # Таск 1: Изчисляване на площта на кръга
- return math.pi * (self.radius ** 2)
- def to_dict(self):
- # Таск 3: Сериализиране на кръга в JSON формат
- return {
- "type": "Circle",
- "attributes": {
- "x": self.x,
- "y": self.y,
- "radius": self.radius
- }
- }
- def __int__(self):
- # Таск 2: Преобразуване на обекта в цяло число (площта на кръга)
- return int(self.area())
- def __str__(self):
- # Таск 2: Връщане на информация за кръга
- return f"Circle at ({self.x}, {self.y}) with radius {self.radius}"
- class Square(Shape):
- def __init__(self, x, y, side_length):
- self.x = x
- self.y = y
- self.side_length = side_length
- def area(self):
- # Таск 1: Изчисляване на площта на квадрата
- return self.side_length ** 2
- def to_dict(self):
- # Таск 3: Сериализиране на квадрата в JSON формат
- return {
- "type": "Square",
- "attributes": {
- "x": self.x,
- "y": self.y,
- "side_length": self.side_length
- }
- }
- def __int__(self):
- # Таск 2: Преобразуване на обекта в цяло число (площта на квадрата)
- return int(self.area())
- def __str__(self):
- # Таск 2: Връщане на информация за квадрата
- return f"Square at ({self.x}, {self.y}) with side length {self.side_length}"
- class Ellipse(Shape):
- def __init__(self, x, y, width, height):
- self.x = x
- self.y = y
- self.width = width
- self.height = height
- def area(self):
- # Таск 1: Изчисляване на площта на елипсата
- return math.pi * (self.width / 2) * (self.height / 2)
- def to_dict(self):
- # Таск 3: Сериализиране на елипсата в JSON формат
- return {
- "type": "Ellipse",
- "attributes": {
- "x": self.x,
- "y": self.y,
- "width": self.width,
- "height": self.height
- }
- }
- def __int__(self):
- # Таск 2: Преобразуване на обекта в цяло число (площта на елипсата)
- return int(self.area())
- def __str__(self):
- # Таск 2: Връщане на информация за елипсата
- return f"Ellipse at ({self.x}, {self.y}) with width {self.width} and height {self.height}"
- # Основна функция за демонстриране на функционалността
- def main():
- shapes = [
- Square(0, 0, 10),
- Rectangle(1, 1, 5, 10),
- Circle(2, 2, 7),
- Ellipse(3, 3, 10, 5)
- ]
- # Таск 3: Запис на формите във файл
- filename = 'shapes.txt'
- with open(filename, 'w') as file:
- for shape in shapes:
- shape.save(filename)
- # Таск 3: Зареждане на формите от файла
- loaded_shapes = Shape.load(filename)
- # Принтиране на информация за всяка заредена форма
- for shape in loaded_shapes:
- print(f"Loaded shape: {shape}")
- print(f"Area: {shape.area()}")
- # Извикване на основната функция
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement