from typing import Generic, TypeVar, List from persistencia.excecoes import EntidadeNaoEncontradaException from modelo.entidade import Entidade T = TypeVar('T', bound=Entidade) class Persistente(Generic[T]): def __init__(self): self.__lista: List[T] = [] def inserir(self, obj: T) -> None: self.__lista.append(obj) def alterar(self, id_: int, novo_obj: T) -> None: if id_ != novo_obj.id: raise ValueError("O id do novo objeto deve ser o mesmo do objeto a ser alterado.") antigo_obj = self.buscar_por_id(id_) index = self.__lista.index(antigo_obj) self.__lista[index] = novo_obj def remover(self, id_: int) -> None: obj = self.buscar_por_id(id_) self.__lista.remove(obj) def buscar_por_id(self, id_: int) -> T: for obj in self.__lista: if obj.id == id_: return obj raise EntidadeNaoEncontradaException(f"ID não encontrado: {id_}") def listar_todos(self) -> List[T]: return self.__lista def __str__(self) -> str: return f"Persistente para o tipo '{T}' com {len(self.__lista)} objetos."