Reputation: 157
I've searched for similar questions, and have not found anything. Apparently because my question is pretty basic, yet I find it hard to understand.
I have a class named Student. In this class I get a name of student, and his grades then calculate his average grade. That one was easy, of course. Here's what I've succeed so far:
class Student:
def __init__(self, name, grades_list):
self.name = name
self.grades_list = grades_list
def get_grade_avg(self):
avg = sum(self.grades_list) / len(self.grades_list)
return avg
def get_name(self):
return self.name
From the previous part I have:
john = Student("John", [100, 90 ,95])
Now I need to answer the following qeustion:
Write a class ClassRoom which has a constructor that receives a list of type Student, and saves this list to a member. The following should create a class room:
class_room = ClassRoom([John])
Implement class ClassRoom such that when calling print(class_room) on a ClassRoom type prints a list of tuples of student name and student grade average, in that order.
Calling print(class_room) should output:
[('John', 95)]
How do I do it?
I'm very new to OOP and have no idea even how to start.
Thank you!
Upvotes: 0
Views: 112
Reputation: 6056
You can do it like this:
class Student:
...
def __repr__(self):
return str((self.name, self.get_grade_avg()))
class ClassRoom:
def __init__(self, students):
self.students = students
def __str__(self):
return str(self.students)
john = Student("John", [100, 90 ,95])
mike = Student("Mike", [90, 80, 85])
c = ClassRoom([john, mike])
print(c)
# [('John', 95.0), ('Mike', 85.0)]
print(c)
When you call print
on some object its __str__
method is invoked and if it is not defined __repr__
is called. By default __repr__
of some object is something like this: <__main__.Student object at 0x7f4b35a3a630>
In the above code a Student
knows how to show itself, (name, avg), so you can print it if you like: print(john)
And for your ClassRoom
, you just need to override __str__
to show the student list. Since every student knows how to show itself, it will do the job.
Upvotes: 1
Reputation: 84
you need to add str() function to both class and student classes. str() if class should iterate over the list of students and print them on by one.
Upvotes: 1