Search code examples
pythonclassoopaverageclass-method

How do I establish the average grade for all students?


I have tried to make a method where I can show the entire average of all students. As you can see in my code, I tried to create an empty list (class-variable) to store the average grade of each student. In my init method I have described that every new student who joins them saves their average grade in the "marklist" list so that I can later define a method that gives me the overall average grade of all students. In order to be able to do this, however, I have to divide the sum of all grade points by the number of students. However, it doesn't work in my program. I'm not quite sure which method to use, whether I can do this with the staticmethod or whether it works with a normal method. I have defined a method "mark_avarage_students_all" that performs the division mentioned. However, performing this method gives me an error because of missing an self argument. Anyone know how I can ultimately output this grade point average for all students? Thanks in advance

Here is my Code:

class Students:

    #class variables
    num_of_students = 0
    #use later to add up all marks from all student
    marklist = []

    def __init__(self, first, last, age, catalognumber, markaverage):
        self.first = first
        self.last = last
        self.age = age
        self.catalognumber = catalognumber
        self.markaverage = markaverage
        self.averageall = Students.marklist.append(self.markaverage)

        Students.num_of_students += 1

    def std_description(self):
        print('My Name is {} {}, I am {} years old.'.format(self.first, self.last, self.age))
        print('My Catalog Number is {} and I have a Mark-average of {}'.format(self.catalognumber, self.markaverage))
        print("")

    @classmethod
    def convert_str(cls, str_std):
        first, last, age, catalognumber, markaverage = str_std.split('-') 
        return cls(first, last, age, catalognumber, markaverage)   

    #calculate the mark average of all students --> sum(marklist) / sum(num_of_students)
    def mark_average_students_all(self):
        return sum(Students.marklist) / Students.num_of_students

if __name__ == '__main__':
    std_1 = 'Jill-Janson-18-20-1.6'
    convert_std_1 = Students.convert_str(std_1)
    convert_std_1.std_description()

    Students.mark_average_students_all()

Solution

  • You defined it as an instance method, but called it from the class. Therefore, the call comes without the implicit self argument. Either call it from an instance, or change the definition to match your usage. The better option is to match the usage: simply declare it as @classmethod and dump the self parameter (which you don't use).