добавил папку

This commit is contained in:
vitalii Malcov 2023-09-12 19:17:10 +02:00
parent 37bccaf0b8
commit fa39aa508e
8 changed files with 143 additions and 0 deletions

View File

@ -0,0 +1,13 @@
import math
from Shape import Shape
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def perimeter(self):
return 2 * math.pi * self.radius
def area(self):
return math.pi + (self.radius ** 2)

View File

@ -0,0 +1,13 @@
from Shape import Shape
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
def perimeter(self):
return 2 * (self.width + self.height)
def area(self):
return self.width * self.height

View File

@ -0,0 +1,23 @@
import math
from abc import abstractmethod
class Shape:
color = ''
@abstractmethod
def area(self):
pass
@abstractmethod
def perimeter(self):
pass
@staticmethod
def convert_to_json(obj):
if isinstance(obj, Shape):
result = obj.__dict__
result['type'] = obj.__class__.__name__
result['color'] = obj.color
return result

View File

@ -0,0 +1 @@
"{'shapes': [{\"width\": 5, \"height\": 10, \"color\": \"red\", \"type\": \"Rectangle\"}, {\"radius\": 7, \"color\": \"blue\", \"type\": \"Circle\"}, {\"side\": 4, \"color\": \"green\", \"type\": \"Square\"}]}"

View File

@ -0,0 +1,12 @@
from Shape import Shape
class Square(Shape):
def __init__(self, side):
self.side = side
def perimeter(self):
return 4 * self.side
def area(self):
return self.side * 2

View File

@ -0,0 +1,61 @@
import json
from Shape import Shape
from Circle import Circle
from Rectangle import Rectangle
from Square import Square
def safe_read(obj, property, default_value):
obj == property
def create_shape(json):
if 'type' in json:
shape_type = json['type'].lower()
if shape_type == 'circle':
if 'radius' in json:
obj = Circle(json['radius'])
else:
obj = Circle(0)
elif shape_type == 'square':
if 'side' in json:
obj = Square(json['side'])
else:
obj = Square(0)
elif shape_type == 'rectangle':
obj = Rectangle(json['width'], json['height'])
else:
raise TypeError(f'вот тебе >>>(оIo), а не фигура {shape_type}')
if 'color' in json:
obj.color = json['color']
else:
obj.color = 'unknown'
return obj
def json_to_python():
data_list = []
with open('shapes.json') as lines:
data = json.load(lines)
for i in data['shapes']:
sh1 = create_shape(i)
data_list.append(sh1)
data2 = '{\'shapes\': ' + json.dumps(data_list, default=Shape.convert_to_json) + '}'
with open('Shapes zwei.json', 'w') as f:
json.dump(data2, f)
print('{\'shapes\': ' + json.dumps(data_list, default=Shape.convert_to_json) + '}')
print(json.dumps({'shapes': data_list}, default=Shape.convert_to_json))
json_to_python()

View File

@ -0,0 +1,20 @@
{
"shapes": [
{
"type": "rectangle",
"width": 5,
"height": 10,
"color": "red"
},
{
"type": "circle",
"radius": 7,
"color": "blue"
},
{
"type": "square",
"side": 4,
"color": "green"
}
]
}