Home > Mobile >  How to return all objects from a class?
How to return all objects from a class?

Time:09-29

I created the following class from which I can "create" students:

import itertools
class Student (object):
    id_iter = itertools.count()
    
    def __init__(self, studentName):
        self.studentName = [studentName, next(self.id_iter)]
    
    def __str__(self):
        return str(self.studentName)

This way, each student gets a unique ID starting from 0. My example list:

stud1 = Student("Justa Student")
stud2 = Student("Another One")
stud3 = Student("One Morestudent")

I'd like to create a function which would return a similar looking list with both the student names and student IDs (I created this list with another, long code):

Desired output list

The output would return all students and their respective IDs. Later on, I'd like to have another function with removing students as well, I'm thinking of making the function with a for loop going until the highest ID, but I can't properly return stuff with the class.

CodePudding user response:

First, I suggest NOT storing both the name and id in a variable named studentName. This is just confusing.

Instead, you can have a separate studentId field:

import itertools
class Student (object):
    id_iter = itertools.count()
    
    def __init__(self, studentName):
        self.studentName = studentName
        self.studentId = next(self.id_iter)]
    
    def __str__(self):
        return str(self.studentName)

Now to create a list, you can make another method that does it:

def createStudents(names):
    return [Student(name) for name in names]

To use this, you have to pass in a list of names:

students = createStudents(["Alice", "Bob", "Charles"])

Now you can print out the list of students with a for loop. I will leave this as an exercise for the reader.

CodePudding user response:

You could create two class methods to store and remove registered students at the class level, meaning you have access to all students that were instantiated by the Student class during your program's process.

import itertools

class Student (object):
    id_iter = itertools.count()
    registeredStudents = {}
    
    def __init__(self, studentName):
        self.studentName = [studentName, next(self.id_iter)]
        self.registeredStudents[self.studentName[0]] = self.studentName[1]
    
    def __str__(self):
        return str(self.studentName)
    
    @classmethod
    def registered_students(cls):
        return [[k, v] for k, v in cls.registeredStudents.items()]
    
    @classmethod
    def remove_student(cls, studentName):
        cls.registeredStudents.pop(studentName)

    
stud1 = Student("Justa Student")
stud2 = Student("Another One")
stud3 = Student("One Morestudent")

print(Student.registered_students())  # [['Justa Student', 0], ['Another One', 1], ['One Morestudent', 2]]
# or
print(stud1.registered_students())  # [['Justa Student', 0], ['Another One', 1], ['One Morestudent', 2]]

# remove student
stud1.remove_student('Justa Student')
# or --> Student.remove_student('Justa Student')
# see remaining students
print(Student.registered_students())  # [['Another One', 1], ['One Morestudent', 2]]
  • Related