import json import random from classes import Shape, Square, Circle, Rectangle def safe_read(obj, property, default_value): if property in obj: return obj[property] return default_value def create_shape(json): if 'type' in json: shape_type = json['type'].lower() if shape_type == 'circle': radius = safe_read(json, 'radius', 0) obj = Circle(radius) elif shape_type == 'square': side = safe_read(json, 'side', 0) obj = Square(side) elif shape_type == 'rectangle': width = safe_read(json, 'width', 0) height = safe_read(json, 'height', 0) obj = Rectangle(width, height) else: raise TypeError(f'вот тебе >>>(оIo), а не фигура {shape_type}') obj.color = safe_read(json, 'color', 'unknown') return obj def generate_shape(): max_length = 100 types = ['square', 'circle', 'rectangle'] colors = ['red', 'green', 'blue', 'yellow', 'black', 'white'] type_index = random.randint(0, len(types) - 1) shape_type = types[type_index] if shape_type == 'circle': obj = Circle(random.randint(1, max_length)) elif shape_type == 'square': obj = Square(random.randint(1, max_length)) elif shape_type == 'rectangle': obj = Rectangle(random.randint(1, 100), random.randint(1, max_length)) else: raise TypeError(f'Происходит что-то непонятное') color_index = random.randint(0, len(colors) - 1) obj.color = colors[color_index] def json_to_python(filename): data_list = [] with open(filename) as lines: data = json.load(lines) for i in data["shapes"]: sh1 = create_shape(i) data_list.append(sh1) return data_list def python_to_json(data, filename): with open(filename, 'w') as f: json.dump({'shapes': data}, f, default=Shape.convert_to_json) def filter_shapes(data, area): return [shape for shape in data if shape.area() >= area] shape_list = json_to_python('shapes.json') shape_list = filter_shapes(shape_list, 100) shape_list.append(generate_shape()) python_to_json(shape_list, 'shape change.json')