Classe generica
This commit is contained in:
		
							parent
							
								
									50b23b07ef
								
							
						
					
					
						commit
						8b96e873ee
					
				| 
						 | 
				
			
			@ -1,29 +1,36 @@
 | 
			
		|||
from typing import Generic, TypeVar, List
 | 
			
		||||
from persistencia.excecoes import EntidadeNaoEncontradaException
 | 
			
		||||
from modelo.entidade import Entidade
 | 
			
		||||
 | 
			
		||||
class Persistente:
 | 
			
		||||
T = TypeVar('T', bound=Entidade)
 | 
			
		||||
 | 
			
		||||
class Persistente(Generic[T]):
 | 
			
		||||
    def __init__(self):
 | 
			
		||||
        self.lista = []
 | 
			
		||||
        self.__lista: List[T] = []
 | 
			
		||||
 | 
			
		||||
    def inserir(self, obj):
 | 
			
		||||
        self.lista.append(obj)
 | 
			
		||||
    def inserir(self, obj: T) -> None:
 | 
			
		||||
        self.__lista.append(obj)
 | 
			
		||||
 | 
			
		||||
    def alterar(self, id_, novo_obj):
 | 
			
		||||
        antigo = self.buscar_por_id(id_)
 | 
			
		||||
        self.lista.remove(antigo)
 | 
			
		||||
        self.lista.append(novo_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_):
 | 
			
		||||
    def remover(self, id_: int) -> None:
 | 
			
		||||
        obj = self.buscar_por_id(id_)
 | 
			
		||||
        self.lista.remove(obj)
 | 
			
		||||
        self.__lista.remove(obj)
 | 
			
		||||
 | 
			
		||||
    def buscar_por_id(self, id_):
 | 
			
		||||
        for obj in self.lista:
 | 
			
		||||
    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):
 | 
			
		||||
        return self.lista
 | 
			
		||||
    def listar_todos(self) -> List[T]:
 | 
			
		||||
        return self.__lista
 | 
			
		||||
 | 
			
		||||
    def __str__(self):
 | 
			
		||||
        return "\n".join(str(obj) for obj in self.lista)
 | 
			
		||||
    def __str__(self) -> str:
 | 
			
		||||
        return f"Persistente para o tipo '{T}' com {len(self.__lista)} objetos."
 | 
			
		||||
		Loading…
	
		Reference in New Issue