Classes review


#1

Hey,

I’m having a hard time on classes, but I am slowly getting there. Why does this line of code print:
[<main.Grade object at 0x7ff2ed460438>]
and not the grade (90) I tried to append?

Thanks in advance

class Student:
def init(self, name, year):
self.name = name
self.year = year
self.grades = []
def add_grade(self, grade):
if type(grade) == Grade:
self.grades.append(grade)
pass

class Grade:
minimum_passing = 65
def init(self, score):
self.score = score
pass

roger = Student(“Roger van der Weyden”, 10)
sandro = Student(“Sandro Botticelli”, 12)
pieter = Student(“Pieter Bruegel the Elder”, 8)

pieter.add_grade(Grade(90))

print(pieter.grades)


#2

Hi @pannemaniac ,

Your code is not formatted, so its indentation is not visible. See How to ask good questions (and get good answers).

The Python interpreter will print a default representation of an instance of a class if you do not define a custom representation for that class. That is what is being displayed. Add a __repr__ method to your Grade class in order to define a more informative representation. Following is an example …

  def __repr__(self):
      return str(self.score)

Then you can do this …

pieter.add_grade(Grade(90))
pieter.add_grade(Grade(80))
pieter.add_grade(Grade(94))
print(pieter.grades)

Output …

[90, 80, 94]

Edited on October 26, 2018 to add some example code.


#3

Thank you!

And thank you for the link to the topic. I will read it.