Python list to store class instance?

后端 未结 3 1082
不思量自难忘°
不思量自难忘° 2021-02-12 23:59

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

3条回答
  •  遥遥无期
    2021-02-13 00:19

    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']
    

提交回复
热议问题