Для реализации классов Point, Vector и контейнера VectorContainer на Python вы можете использовать следующий код:
import json
from typing import List
class Point:
def __init__(self, x=0, y=0, z=0):
self.x = x
self.y = y
self.z = z
@classmethod
def from_string(cls, string):
coordinates = list(map(float, string.split(',')))
return cls(*coordinates)
def to_json(self):
return json.dumps({'x': self.x, 'y': self.y, 'z': self.z})
@classmethod
def from_json(cls, json_string):
data = json.loads(json_string)
return cls(data['x'], data['y'], data['z'])
def __str__(self):
return f"Point({self.x}, {self.y}, {self.z})"
def distance_to(self, other):
return ((self.x - other.x)**2 + (self.y - other.y)**2 + (self.z - other.z)**2)**0.5
def __eq__(self, other):
return self.x == other.x and self.y == other.y and self.z == other.z
def __add__(self, vector):
return Point(self.x + vector.x, self.y + vector.y, self.z + vector.z)
class Vector(Point):
def length(self):
return self.distance_to(Point(0, 0, 0))
def dot_product(self, other):
return self.x * other.x + self.y * other.y + self.z * other.z
def cross_product(self, other):
return Vector(self.y * other.z - self.z * other.y,
self.z * other.x - self.x * other.z,
self.x * other.y - self.y * other.x)
def __str__(self):
return f"Vector({self.x}, {self.y}, {self.z})"
class VectorContainer:
def __init__(self):
self.vectors = []
def add_vector(self, vector):
self.vectors.append(vector)
def remove_vector(self, vector):
self.vectors.remove(vector)
def to_json(self):
return json.dumps([vector.to_json() for vector in self.vectors])
@classmethod
def from_json(cls, json_string):
container = cls()
vectors_data = json.loads(json_string)
for vector_data in vectors_data:
vector = Vector.from_json(vector_data)
container.add_vector(vector)
return container
# Additional useful methods can be implemented here.
Пример использования классов:
# Создание точки из строки
point_from_string = Point.from_string("1.0,2.0,3.0")
print(point_from_string) # Output: Point(1.0, 2.0, 3.0)
# Создание вектора и сохранение его в JSON
vector = Vector(1, 2, 3)
json_vector = vector.to_json()
print(json_vector) # '{"x": 1, "y": 2, "z": 3}'
# Загрузка вектора из JSON
loaded_vector = Vector.from_json(json_vector)
print(loaded_vector) # Vector(1, 2, 3)
# Создание контейнера, добавление векторов, сохранение и загрузка из JSON
container = VectorContainer()
container.add_vector(vector)
container.add_vector(Vector(4, 5, 6))
json_container = container.to_json()
loaded_container = VectorContainer.from_json(json_container)
for vec in loaded_container.vectors:
print(vec)
Этот код содержит три класса:
Point: описывает точку в трехмерном пространстве.
Vector: наследуется от Point и описывает вектор, добавляет методы для работы с векторами.
VectorContainer: контейнер для хранения векторов, с методами для добавления/удаления векторов и сохранения/загрузки из JSON.
В данном примере класс Vector наследуется от класса Point, так как вектором можно считать направленный отрезок из начала координат в данную точку, отсюда унаследованные свойства точки хорошо подходят для описания вектора.