I have a question about how to use the "NAME" of a class instance. If I declare it directly:
Sala_10 = Sala("Sala_10")
works fine. I can use Sala_10.método()
, but I would like to instantiate the rooms through a function, called add_sala(id)
.
I even create the normal room, but I do not know how to reference this room ... of course, I get the error message:
NameError: name 'Sala_10' is not defined
My code goes below, thanks!
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)
It works fine, but if you do:
add_sala("Sala_9B")
for i in range(len(salas)):
print(salas[i].id)
It does not work! How to use the reference passed below as the name of the object to invoke it after?
Now I'm going to use the room Sala_9B
created by the function add_sala()
how to use to correctly 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/Program_Council/examples-help/test-myclass.py", line 44, in Sala_9B.add_alunos (1, "Sepúlveda Pertence") NameError: name 'Sala_9B' is not defined