2023-09-03 10:53:21 +02:00
|
|
|
import json
|
|
|
|
from abc import abstractmethod
|
|
|
|
from abc import ABC
|
|
|
|
import math
|
|
|
|
|
|
|
|
|
|
|
|
class Shape(ABC):
|
|
|
|
color = ''
|
|
|
|
|
|
|
|
@abstractmethod
|
|
|
|
def area(self):
|
|
|
|
pass
|
|
|
|
|
|
|
|
@abstractmethod
|
|
|
|
def perimetr(self):
|
|
|
|
pass
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def create_shape(json):
|
|
|
|
if "type" in json:
|
2023-09-18 21:20:56 +02:00
|
|
|
shape_type = json["type"].lower()
|
2023-09-03 10:53:21 +02:00
|
|
|
if shape_type == "circle":
|
2023-09-25 14:39:15 +02:00
|
|
|
radius = 'radius'
|
2023-09-03 10:53:21 +02:00
|
|
|
elif shape_type == "square":
|
2023-09-25 14:39:15 +02:00
|
|
|
side = 'side'
|
2023-09-03 10:53:21 +02:00
|
|
|
elif shape_type == "rectangle":
|
|
|
|
return Rectangle(json["width"], json["height"])
|
|
|
|
else:
|
|
|
|
raise TypeError(f'Неизвестная фигура {shape_type}')
|
2023-09-18 21:20:56 +02:00
|
|
|
shape_type.color = safe_read(json, "color", "unknown")
|
|
|
|
|
2023-09-03 10:53:21 +02:00
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def convert_to_json(obj):
|
|
|
|
if isinstance(obj, Shape):
|
|
|
|
result = obj.__dict__
|
|
|
|
result["type"] = obj.__class__.__name__
|
2023-09-25 14:39:15 +02:00
|
|
|
result['color'] = obj.color
|
2023-09-18 21:20:56 +02:00
|
|
|
return result
|
|
|
|
|
|
|
|
def safe_read (shape_type, property, default_value):
|
|
|
|
if property in shape_type:
|
|
|
|
return shape_type[property]
|
|
|
|
return default_value
|
|
|
|
|
2023-09-03 10:53:21 +02:00
|
|
|
|
|
|
|
|
|
|
|
class Rectangle(Shape):
|
|
|
|
def __init__(self, width, height):
|
|
|
|
self.width = width
|
|
|
|
self.height = height
|
|
|
|
|
|
|
|
def area(self):
|
|
|
|
return self.width * self.height
|
|
|
|
|
|
|
|
def perimetr(self):
|
|
|
|
return (self.width + self.height) * 2
|
|
|
|
|
|
|
|
|
|
|
|
class Square(Shape):
|
|
|
|
def __init__(self, side):
|
|
|
|
self.side = side
|
|
|
|
|
|
|
|
def area(self):
|
|
|
|
return self.side ** 2
|
|
|
|
|
|
|
|
def perimetr(self):
|
|
|
|
return 4 * self.side
|
|
|
|
|
|
|
|
|
|
|
|
class Circle(Shape):
|
|
|
|
def __init__(self, radius):
|
|
|
|
self.radius = radius
|
|
|
|
|
|
|
|
def area(self):
|
|
|
|
return math.pi * (self.radius ** 2)
|
|
|
|
|
|
|
|
def perimetr(self):
|
|
|
|
return 2 * math.pi * self.radius
|
|
|
|
|
|
|
|
|
|
|
|
r1 = Rectangle(10, 20)
|
|
|
|
s1 = Square(22)
|
|
|
|
c1 = Circle(10)
|