Problem in Inserting an Array

1

Well, I'm trying to learn python because it seems to me a language with some interesting applicability in the most diverse areas (and I'm interested in raspberry).

As I am learning, I like to go about something that I need to apply the knowledge.

As such I am developing a system consisting of a class dictionary (Class Created) whose identifier of each class is the acronym received.

Each class consists of an array of students (Created Class) and an acronym that identifies it.

All classes have setters and getters for all attributes.

My problem is that whenever I add a new student to a class already created and inserted into the class array, it adds it to all classes contained in the array and I can not find the focus of the problem.

The code for my class class is as follows:

class Turma:
   nome = None
   sigla = None
   alunos = []
   def __init__(self, _nome, _sigla):
       self.nome = _nome
       self.sigla = _sigla
   def getNome(self):
       return self.nome
   def addAluno(self, _aluno):
       self.alunos.append(_aluno)
   def getSigla(self):
       return self.sigla
   def getAlunos(self):
       return self.alunos

The code for my student class is as follows:

class Aluno:
   nome = None
   idade = None
   numero = None
   def __init__(self, _nome, _idade, _num):
       self.nome = _nome
       self.idade = _idade
       self.numero = _num
   def getNome(self):
       return self.nome
   def getNumero(self):
       return self.numero
   def getIdade(self):
       return self.idade
   def setNome(self, _nome):
       self.nome = _nome
   def setIdade(self, _idade):
       self.idade = _idade
   def setNome(self, _num):
       self.numero = _num

In my system control file I have the following features:

turmas = {}
def createTurma():
   nome = input("Insira o nome da turma: ")
   sigla = input("Insira a sigla da turma: ")
   turmas[sigla] = Turma(nome, sigla)
   print(turmas);
   print("Turma Adicionada com Sucesso!")

def listTurma():
   sigla = input("Insira a sigla do curso: ")
   print(turmas[sigla].getNome())

def addAlunoTurma():
   num = 0
   nome = input("Insira o nome do aluno: ")
   idade = input("Insira a idade do aluno: ")
   sigla = input("Insira a sigla da turma: ")
   _aluno = Aluno(nome, idade, 0)
   turmas[sigla].addAluno(_aluno)

def getAlunosByTurma():
   sigla = input("Insira a sigla da turma: ")
   teste = turmas[sigla].getAlunos()
   print(len(teste))
   for i in turmas[sigla].getAlunos():
       print("Nome: " + i.getNome())
       print("Numero: " + str(i.getNumero()))
       print("--------------")

I detected this problem when the function getAlunosByTurma () because regardless of the acronym always prints all students.

Thank you !!

    
asked by anonymous 13.06.2016 / 22:55

2 answers

0

Your problem is in this class class declaration, together with an error common with those who come from Java to Python:

class Turma:
   nome = None
   sigla = None
   alunos = []
   def __init__(self, _nome, _sigla):
       self.nome = _nome
       self.sigla = _sigla

The "declaration of variables" in the class body is incorrect and unnecessary in Python: this creates attributes of the class and not for each instance as it exists in Java.

As a rule, this is not a problem because when you create a value for self.nome in __init__ , with self.nome = nome , an attribute is created in the instance of the object that "hides" the class attribute. / p>

But in the case of alunos you create an empty list - and your methods do not create a new list - they only manipulate the list in self.alunos . If there is no instance attribute that is self.alunos , Python automatically accesses the attribute in self.__class__.alunos - which is a single list that is shared by all its instances of Turma .

Correcting this is pretty easy - just change the beginning of your Turma statement to:

class Turma: 
   def __init__(self, _nome, _sigla):
       self.nome = _nome
       self.sigla = _sigla
       self.alunos = []

Another tip: the literal object built with [] is a "list" (list), not an "array". You can use the word "list" yourself. And another: there is no need, d prefix local variables with "" - you should have read that it is convened that private attributes and methods are prefixed with "" - yes, the entnaot this is a convention - there is nothing magic about the language about variables that start with _ (but there are for attributes that start with two __ , care). In addition, you are prefixing local variables of methods with "_" - these variables are internal to methods, and are not visible "from the outside" - there is no gain - nor conventional - in calling your parameter _idade and not idade - but you lose readability and ease of typing.

And as I said above, you generally do not need getters and setters: your program will work just as well if you want to change a student's age to make "student.hood = 12" rather than "student.setty ( 12) "- Because of the GIL, these direct assignments are thread safe. And if at some point you want to put a guard on the attributes (the system has grown and you want to avoid ages other than positive integers greater than 5, for example) - then you write the getter and the setter, but using "property" Python - users in your class keep typing aluno.idade = 12 but this time the assignment goes through the setter method.

    
14.06.2016 / 20:35
0

I'm not sure how your classes are structured, but I have an idea of the program you are doing. I made a small example that I think I can give you a few lights. Here, using dictionaries we have been able to store relevant information for students and their students classes

turmas = []

def createTurma():
   nome = input("Insira o nome da turma: ")
   sigla = input("Insira a sigla da turma: ")
   turmas.append({'nome': nome, 'sigla': sigla, 'alunos': []})

def addAlunoTurma():
   num = 0
   nome = input("Insira o nome do aluno: ")
   idade = input("Insira a idade do aluno: ")
   sigla = input("Insira a sigla da turma: ")
   if any(turma['sigla'] == sigla for turma in turmas): # verificamos se a sigla existe
        for turma in turmas:
            if sigla == turma['sigla']:
                turma['alunos'].append({'nome': nome, 'idade': idade})
                break
   else:
        print('turma não existe')

createTurma()
print(turmas)
addAlunoTurma()
print(turmas)
addAlunoTurma()
print(turmas)

As an example, here we will add a class and two students, in the end we will have the classes in this format:

[{'nome': 'turma B1', 'sigla': 'B1', 'alunos': [{'nome': 'Miguel', 'idade': '30'}, {'nome': 'caoc10', 'idade': '25'}]}]

In order to access the data of the first class, you would:

turmas[0] # {'nome': 'turma B1', 'sigla': 'B1', 'alunos': [{'nome': 'Miguel', 'idade': '30'}, {'nome': 'caoc10', 'idade': '25'}]}
    
13.06.2016 / 23:22