Given a python class class Student():
and a list names = []
; then I want to create several instances of Student()
and add them into the li
I'm fairly new to OOP, but does this not do what you want quite nicely? name_list
is a class variable, and every time you create a new Student
object, it gets added to Student.name_list
. Say for example you had a method cheat(self)
which you wanted to perform on the third student, you could run Student.name_list[2].cheat()
. Code:
class Student():
name_list = []
def __init__(self, score, gender):
Student.name_list.append(self)
self.score = score
self.gender = gender
#this is just for output formatting
def __str__(self):
return "Score: {} || Gender: {}".format(self.score, self.gender)
#again for output formatting
def update(): print([str(student) for student in Student.name_list])
update()
Student(42, "female")
update()
Student(23, "male")
update()
Student(63, "male")
Student(763, "female")
Student("over 9000", "neutral")
update()
Output:
[]
['Score: 42 || Gender: female']
['Score: 42 || Gender: female', 'Score: 23 || Gender: male']
['Score: 42 || Gender: female', 'Score: 23 || Gender: male', 'Score: 63 || Gender: male', 'Score: 763 || Gender: female', 'Score: over 9000 || Gender: neutral']