Home > Back-end >  How can I pass a class object as an argument into a different class method?
How can I pass a class object as an argument into a different class method?

Time:12-05

I have two classes :

Classroom which holds students as a list. And Student

Everytime I update a score of a student, I want to call calculate_average for the Classroom he/she is in. Below code does not work for obvious reasons since I don't know how to give the Classroom a student is in as a function argument.

class Classroom:
    students = None

    def __init__(self):
        self.students = []

    def addStudent(self, student):
        self.students.append(student)

    def calculate_average(self):
        # sums student scores and divides them with student number

class Student:
    def __init__(self, name, score):
        self.name = name
        self.score = score

    def getInfo(self):
        return self.name, self.score

    def setScore(self, score):
        self.score = score
        Classroom.calculate_average()

How can I make this work ?

CodePudding user response:

class Classroom:
    def __init__(self):
        self.students = []

    @property
    def average(self):
        return sum(student.score for student in self.students)/len(self.students)

class Student:
    def __init__(self, name, score):
        self.name = name
        self.score = score

    def __repr__(self):
        return f"Student(name={self.name}, score={self.score})"


student_1 = Student("John Doe", 10)
student_2 = Student("Jane Doe", 20)

clasroom_1 = Clasroom()

clasroom_1.students.append(student_1)
clasroom_1.students.append(student_2)

clasroom_1.average # 15

student_1.score = 30

clasroom_1.average # 25

Use what python supplies you with. property, property(f).setter, __repr__.

And please do follow pep8 and use snake_case and not camelCase

CodePudding user response:

Assuming several Students share the same ClassRoom, you probably want to create a named Classroom instance, then pass that in to a Student class when instantiating it. Something like:

class Classroom():
    def __init__(self):
        self.students = []

    def addStudent(self, student):
        self.students.append(student)

    def calculate_average(self):
        return sum(x.score for x in self.students if hasattr(x, 'score')) / len(self.students)

class Student():
    def __init__(self, classroom):
        self.classroom = classroom
        self.classroom.addStudent(self)

    def setScore(self, score):
        self.score = score

classroom1 = Classroom()
student1 = Student(classroom1)
student2 = Student(classroom1)

student1.setScore(100)
student2.setScore(50)
print(classroom1.calculate_average())
# 75
  • Related