Загружаю доработанное ДЗ по json

This commit is contained in:
ehermakov 2023-09-03 11:53:21 +03:00
parent f8df1e5fa0
commit 74e980176d
2 changed files with 83 additions and 3 deletions

View File

@ -0,0 +1,75 @@
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:
shape_type = json["type"]
if shape_type == "circle":
return Circle(json["radius"])
elif shape_type == "square":
return Square(json["side"])
elif shape_type == "rectangle":
return Rectangle(json["width"], json["height"])
else:
raise TypeError(f'Неизвестная фигура {shape_type}')
@staticmethod
def convert_to_json(obj):
if isinstance(obj, Shape):
result = obj.__dict__
result["type"] = obj.__class__.__name__
return json.dumps(result)
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)

View File

@ -1,7 +1,9 @@
import json
from shape import Shape
from classes import Shape, Square, Circle, Rectangle
def json_to_python():
data_list = []
with open("shapes.json") as lines:
data = json.load(lines)
for i in data["shapes"]:
@ -9,8 +11,11 @@ def json_to_python():
print("Type:", i["type"])
print("Color:", i["color"])
sh1 = Shape.create_shape(i)
print(sh1)
print(f'area = {sh1.area()}')
print(f'perimetr = {sh1.perimetr()}')
data_list.append(sh1)
for j in data_list:
print(j.convert_to_json(j))
return "Программа завершена"