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.
– Isac
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.– Isac