Хорошо, ниже я предоставлю расширенные версии файлов с полной логикой, в том числе с обработкой ошибок при чтении/записи файлов JSON.
point.py:
import json
class Point:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
@classmethod
def from_string(cls, s):
try:
x, y = map(float, s.split(','))
return cls(x, y)
except (ValueError, TypeError) as e:
raise ValueError(f"Unable to create a Point from string '{s}': {e}")
def to_json(self, filepath):
try:
with open(filepath, 'w') as file:
json.dump({'x': self.x, 'y': self.y}, file)
except IOError as e:
raise IOError(f"Unable to write to file '{filepath}': {e}")
@classmethod
def from_json(cls, filepath):
try:
with open(filepath, 'r') as file:
data = json.load(file)
return cls(**data)
except IOError as e:
raise IOError(f"Unable to read from file '{filepath}': {e}")
except ValueError as e:
raise ValueError(f"Data is not a valid Point representation: {e}")
# Определение других методов или свойств
def __repr__(self):
return f"Point({self.x}, {self.y})"
vector.py:
import json
from point import Point
class Vector(Point):
def __init__(self, x=0, y=0):
super().__init__(x, y)
def magnitude(self):
return (self.x**2 + self.y**2)**0.5
def add(self, other):
if isinstance(other, Vector):
return Vector(self.x + other.x, self.y + other.y)
else:
raise TypeError("The operand must be a Vector instance.")
# Это пример метода сохранения в JSON
def to_json(self, filepath):
super().to_json(filepath)
# Это пример метода загрузки из JSON
@classmethod
def from_json(cls, filepath):
return super().from_json(filepath)
# Другие методы или свойства
def __repr__(self):
return f"Vector({self.x}, {self.y})"
container.py:
import json
from vector import Vector
class Container:
def __init__(self):
self.items = []
def add(self, item):
if isinstance(item, Vector):
self.items.append(item)
else:
raise TypeError("The item must be a Vector instance.")
def remove(self, item):
if item in self.items:
self.items.remove(item)
else:
raise ValueError("The item was not found in the container.")
def to_json(self, filepath):
try:
with open(filepath, 'w') as file:
json.dump([item.__dict__ for item in self.items], file)
except IOError as e:
raise IOError(f"Unable to write to file '{filepath}': {e}")
def from_json(self, filepath):
try:
with open(filepath, 'r') as file:
items_data = json.load(file)
self.items = [Vector(**data) for data in items_data]
except IOError as e:
raise IOError(f"Unable to read from file '{filepath}': {e}")
except TypeError as e:
raise ValueError(f"Data is not a valid representation of Vectors: {e}")
def __repr__(self):
return f"Container({self.items})"
# Документация классов и методов
main.py:
from geometry.point import Point
from geometry.vector import Vector
from geometry.container import Container
from examples.examples import run_examples
def menu():
container = Container()
while True:
print("\nMenu:")
print("1. Add a new vector")
print("2. Remove a vector")
print("3. Save to JSON")
print("4. Load from JSON")
print("5. Run examples")
print("6. Exit")
choice = input("Enter your choice: ")
if choice == '1':
x = float(input("Enter x for the vector: "))
y = float(input("Enter y for the vector: "))
vector = Vector(x, y)
container.add(vector)
print("Vector added to the container.")
elif choice == '2':
index = int(input("Enter the index of the vector to remove: "))
try:
vector_to_remove = container.items[index]
container.remove(vector_to_remove)
print("Vector removed from the container.")
except IndexError:
print("Invalid index.")
elif choice == '3':
filepath = input("Enter file path to save JSON: ")
try:
container.to_json(filepath)
print("Container saved to JSON.")
except IOError as e:
print(e)
elif choice == '4':
filepath = input("Enter file path to load JSON: ")
try:
container.from_json(filepath)
print("Container loaded from JSON.")
except (IOError, ValueError) as e:
print(e)
elif choice == '5':
run_examples()
elif choice == '6':
break
else:
print("Invalid choice, please try again.")
if __name__ == "__main__":
menu()
examples.py:
from geometry.point import Point
from geometry.vector import Vector
from geometry.container import Container
def run_examples():
print("\nRunning examples...")
# Пример 1: Создание точки из строки и преобразование в JSON
point = Point.from_string("1,2")
print(f"Created Point from string: {point}")
point_json_path = "example_point.json"
point.to_json(point_json_path)
print(f"Point saved to JSON: {point_json_path}")
# Пример 2: Создание вектора из JSON
loaded_point = Point.from_json(point_json_path)
print(f"Point loaded from JSON: {loaded_point}")
# Примеры работы с вектором
vector1 = Vector(2, 3)
vector2 = Vector(5, 7)
sum_vector = vector1.add(vector2)
print(f"Sum of vectors: {vector1} + {vector2} = {sum_vector}")
# Примеры работы с контейнером
container = Container()
container.add(vector1)
container.add(vector2)
print(f"Container after adding vectors: {container}")
container.remove(vector1)
print(f"Container after removing a vector: {container}")
# И еще больше примеров...
print("Examples finished.")
if __name__ == "__main__":
run_examples()
Вы можете скопировать каждый блок кода в соответствующие файлы, сохранить и запустить main.py для взаимодействия с программой через командную строку. Помните, что чтобы сохранять или загружать данные из файлов JSON, файлы должны существовать и быть доступные для чтения/записи.