How do I access the name of a class instance to use later?

Asked

Viewed 79 times

2

I have a question how to use the "NAME" of a class instance. If I declare it directly:

Sala_10 = Sala("Sala_10") 

works well. I can use the Sala_10.método(), but I would like to create (instantiate) the rooms through a function, called add_sala(id).

I even create the normal room, but I don’t know how to reference this room... of course, I get the error message:

Nameerror: name 'Sala_10' is not defined

my code goes down, thank you!

test-myclass.py

salas = []

class Sala:

    def __init__(self, id):

        self.id = id

        self.alunos = []  # lista de alunos da sala.

    def add_alunos(self, num, nome):
        nome = Aluno(num, nome)  # -> cria o objeto ALUNO
        self.alunos.append(nome)


class Aluno:
    def __init__(self, num, nome):
        self.num = num
        self.nome = nome


def add_sala(id):  # função para criar e adicionar SALAS
    nome = Sala(id)  # cria uma nova sala chamada: o valor da variável x
    salas.append(nome)

When I do:

Sala_9A = Sala("Sala_9A")
Sala_9A.add_alunos(1, "Austregésilo de Athayde")
print(Sala_9A.alunos[0].nome)

Works ok, but if you do:

add_sala("Sala_9B")

for i in range(len(salas)):
    print(salas[i].id)

It doesn’t work! How to use the reference passed below as the object name to invoke it later?

Now I’m gonna use the room Sala_9B created by the Function add_sala() how to use to properly access this instance of the Room class ?

Sala_9B.add_alunos(1, "Sepúlveda Pertence")
print(Sala_9B.alunos[0].nome)

Traceback (Most recent call last): File "/home/Bueno/Programming/Programa_advice/examples-help/test-myclass.py", line 44, in Sala_9b.add_alunos(1, "Sepúlveda Pertence") Nameerror: name 'Sala_9b' is not defined

  • Try your best to apply the formatting provided by the editor. It has both the button to format the code, with the quote that will be appropriate for error messages. Considering that I changed a lot of things, look how the question turned out, and if it reflects your original doubt.

  • Regarding the question, whether the instance was created within the add_sala so you didn’t get any variables that referenced it. So you have to access from the same room list.

1 answer

1

Your Classroom class seems kind of lazy or "useless", since it only serves to add students, maybe it is a better way to use a dictionary and have the name of the room as a key. Something like that:

salas = {}

class Aluno:
    def __init__(self, num, nome):
        self.num = num
        self.nome = nome

    def __str__(self):
        return self.nome


def add_sala(id_sala):  # função para criar e adicionar SALAS
    if id_sala not in salas:
        salas[id_sala] = []  # cria uma nova sala com o nome passado em id_sala
    else:
        print('Sala já existente!')

def add_alunos(num, nome, id_sala): # -> Melhor seria passar o aluno já criado para diminuir o acoplamento
    nome = Aluno(num, nome)  # -> cria o objeto ALUNO
    salas[id_sala].append(nome)

add_sala('Sala-B9') # -> adiciona nova sala
print(salas.keys()) # -> mostra salas existentes
print(salas['Sala-B9']) # -> mostra alunos da sala apontada
add_alunos(10, 'Matheus', 'Sala-B9') # -> adiciona aluno a Sala-B9
print(salas['Sala-B9'][0]) # -> mostra o primeiro aluno na Sala-B9
# pode ser feito um for para todos os alunos assim: for aluno in salas['Sala-B9']: ...
add_sala('Sala-B9') # -> tentando adicionar sala já existente, a sala não é sobrescrita
add_sala('Sala-A10') # -> adiciona outra sala
print(salas.keys()) # -> mostra salas existentes
  • Thanks for the answer, I agree with you, that my example is quite reduced (is that I have deleted several other class features, such as changing student data, etc, and a few more steps that I will add). I will consider your suggestion to use dictionaries... very valid. But if I follow my original idea, I insist on asking if it is possible to access class methods if it is created through the add_sala() function, or just by accessing the rooms[] list? What I’m already doing and it’s working fine....

  • This is the right answer - if you have a fixed number of rooms, which will be individually accessed for different things at different points in the program, you associate the same with variables - and then you create one by one in your code explicitly. If you’re going to create rooms dynamically, and you only need one identifier to get to the same room, the correct thing is to use a dictionary - in this case the identifier of the room is just one more datum , is not part of the code. You don’t even need the function - you can do a Dict-comprehension like: salas = {f"sala_{i:02d}": Sala(i) for i in range(10)}

  • Perhaps this modeling is not very easy to understand, because your idea is that a room manages itself, which does not happen in real life. Someone, unlike the student and classroom objects, generates a relationship between these two, making it possible for them to interact with each other. If your idea really is to use a class that is responsible for relating students and classrooms, I will link a code so that you can take a look, if, in your model, your Classroom class actually has behaviors that are proper to a Classroom object, then you can adapt whatever you need. link

Browser other questions tagged

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