Python Object Oriented Programming

So I was reviewing the Introduction to Classes in Python and here is the code

class Student:
  def __init__(self, name, year):
    self.name = name
    self.year = year
    self.grades = []
  
  def __repr__(self):
    return self.name
  
  def add_grade(self, grade):
    if type(grade) is Grade:
      self.grades.append(grade)
    else:
      pass

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

class Grade:
  minimum_passing = 65
  def __init__(self, score):
    self.score = score
  def is_passing(self):
    if self.score >= self.minimum_passing:
      print("Pass")
    else:
      print("Fail")

seventy = Grade(70)
#seventy.is_passing()

pieter.add_grade(Grade(100))
pieter.add_grade(Grade(98))
pieter.add_grade(Grade(64))
pieter.add_grade(Grade(97))

print(pieter.grades)

In the above code, I wanted to view Pieters grades, but the code returned me the following answer

Screenshot 2024-01-13 123904

# You wrote:
def add_grade(self, grade):
    if type(grade) is Grade:
        self.grades.append(grade)
    else:
        pass

When you make the calls

pieter.add_grade(Grade(100))
# and so on...

you are passing an instance of the Grade class as the argument to add_grade. Within add_grade, you are appending this object to self.grades. Therefire, the output of your print statement print(pieter.grades) is a list of Grade objects.

If your intention is not to append the Grade objects but the actual scores, then you can amend your add_grade to:

# You wrote:
if type(grade) is Grade:
    self.grades.append(grade)

# Change to:
if type(grade) is Grade:
    self.grades.append(grade.score)

Once you make the above change, your output will be:

print(pieter.grades)
# [100, 98, 64, 97]

However, if your intention is to append the Grade object and then extract the score later, then you should see the suggestions in this post:

or this post:

1 Like