Crud with Python

Asked

Viewed 3,216 times

0

What would be the problem with these codes?

Someone could guide me which is the best practice to make a system of registration, editing, exclusion and consultation?

First code:

class Cadastro:
  def __init__(self):
    self.nome = input('Digite nome do aluno: ')
    self.senha = input('Digite a senha: ')


  def aluno(self, nome, senha):
    self = Cadastro()
    self.nome = ' ' 
    self.senha = ' '
    return self

Second code:

class Cadastro:
  def __init__(self):
    self.nome = input('Digite nome do aluno: ')
    self.senha = input('Digite a senha: ')

  def aluno(self, nome, senha):
    self = Cadastro()
    self.nome = input('Digite nome do aluno: ')
    self.senha = input('Digite a senha: ')
    return self

Third code:

**from lista import * list = [] while True:

opc = int(input('Cadastrar, digite 1\nConsultar, digite 2 \nOpção: '))
print()
if opc == 1:
    banco = (NovaConta())
    lista.append(banco)
    print('Cadastrado com sucesso! \nID: %i \nCliente: %s \nConta: %i '
          %(banco.ID, banco.cliente, banco.conta))
    print('-'*25)
elif opc == 2:

    consulta = int(input('Digite o ID: '))
    if consulta not in lista:
        print('Não contém')
    else:
        print(consulta[lista])**

And saved this file with the following list name.py:

class usuario:
    ID = 0
    cliente = ' '
    conta = 0


def NovaConta():
    nc = usuario() 
    nc.ID = int(input('Digite um ID): '))
    nc.cliente = input('Digite Nome: ')
    nc.conta = int(input('Digite número da conta: '))
    print()
    return nc

2 answers

1


Best practice is to isolate your interface logic from data logic. Your class Students don’t have to know or depend on the interface, and their interface should control as little logic as possible related to a student.

Modularized code (that is, with components as independent as possible from each other) bring some advantages:

  • Better code organization (each system can be in its own file/folder/repository, depending on the size of the project)
  • Better bug isolation (a bug in an isolated system hardly has cause in another system, and therefore is easier to find)
  • You have the freedom to modify or even fully restore a system without breaking the whole program

So, for your example of enrolling students, using only the basic structures of Python, a good program would follow patterns like this:

class Aluno:

    def __init__(self, nome, senha):  # Assim, você pode facilmente criar um aluno
        self.nome = nome
        self.senha = senha

    def mudar_senha(self, senha_antiga, senha_nova):
        if self.senha == senha_antiga:
            self.senha = senha_nova
            return True  # Sucesso
        else:
            return False  # Senha atual não confere

class Interface:

    alunos = []

    def cadastrar_aluno(self):
        nome = input('Quais é o nome do aluno?\n')
        senha = input('Quais é a senha desejada?\n')

        self.alunos.append(Aluno(nome, senha))
        print('Aluno adicionado!')

    def listar_alunos(self):
        for i, aluno in enumerate(self.alunos):
            print(i, aluno.nome)

    def mudar_senha(self):
        numero_aluno = input('Qual é o número de listagem do aluno?')
        numero_aluno = int(numero_aluno)

        senha_antiga = input('Quais é a senha atual?\n')
        senha_nova = input('Quais é a senha nova desejada?\n')
        sucesso = self.alunos[numero_aluno].mudar_senha(senha_antiga, senha_nova)

        if sucesso:
            print('Alteração realizada!')
        else:
            print('Erro ao tentar alterar senha!')


    def loop(self):
        while True:
            cmd = input('\n1 - Listar alunos\n2 - Cadastrar aluno\n3 - Mudar senha\n')
            if cmd == '1':
                self.listar_alunos()
            elif cmd == '2':
                self.cadastrar_aluno()
            elif cmd == '3':
                self.mudar_senha()
            else:
                print('Não entendi!')
                continue


if __name__ == '__main__':
    interface = Interface()
    interface.loop()

Notice that the class Aluno does not know anything about the interface, and the interface does not take care of any class logic Aluno. For example, the function mudar_senha of the interface takes the desired data, but does not directly touch the student’s password; this change logic is within the class Aluno.

Thus, you could easily exchange the text interface for a graphic and keep all your class code Aluno.

  • Thanks! I’ll try to understand.

  • Pedro. Good evening! So, I am evaluating your code first and I was doubtful. def listar_alunos(self): for i, aluno in enumerate(self.alunos): print(i, aluno.nome) esse for concatenating i and that variable student what role they play. That was one of the doubts. Gratefully!

  • The function list students shows on the screen the student’s number and then his name. The loop for iterate over the list alunos given, and for each element in the list gives the name aluno and executes what is inside your block. The enumerate causes instead of only returning each element of the list, the for also return the element number. I mean, when the is passed by the first student the value of i is 0, the second is 1, and so on. So when we do print(i, aluno.nome), we are printing the number of each element of the list alunos and the corresponding student’s name.

  • My doubt, was no for enumerate. Valeu Pedro!

  • Good morning Pedro! What does this part of the code do? f name == 'main': interface = Interface() interface.loop() Would you be so kind as to use it in another simple example? I’ve never seen it and I’m seeing it now constantly and I can’t understand what it does. Grateful.

  • Oops! Basically, it serves to run the code only if the main file is called. This serves to avoid multiprocessing confusions and to have different behavior when importing a file as a module or running it directly. Here are some questions with more comprehensive answers: 1 2

  • From what I understand, main is a function that loads a file without having to invoke the function. Correct, more or less that?

Show 2 more comments

0

Your registration class could be like this:

import random

class Cadastro:
    def __init__(self):
    self.__nome = input('Digite nome do aluno: ')
    self.__senha = input('Digite a senha: ')
    self.__conta = self.__gerar_conta()

    def __repr__(self):
        return "Cadastro(['nome': '{}', 'senha': '{}', 'conta': '{}'])".format(
        self.__nome, self.__senha, self.__conta
    )

    def __gerar_conta(self):
        return random.choice(range(3124, 9458))

    @property
    def nome(self):
        return self.__nome

    @property
    def senha(self):
        return self.__senha

    @property
    def conta(self):
        return self.__conta

opcao = 0
contas = {}

while opcao != 3:
    opcao = int(input('\n\nCadastrar, digite 1\nConsultar, digite 2 \nPara sair, digite 3\nOpção: '))

    if opcao == 1:
        print('\n\nCadastrando novo usuário...')
        cadastro_novo = Cadastro()
        contas[cadastro_novo.conta] = cadastro_novo
        print(cadastro_novo)
    elif opcao == 2:
        conta = int(input('\n\nDigite o numero da conta: '))
        if conta in contas.keys():
            print(contas[conta])
        else:
            print('Conta #{} não existe.'.format(conta))
    elif opcao == 3:
        print('\n\nSaindo.')
    else:
        print('\n\nOpcao invalida.')
  • Thank you! I will try to understand here.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.