Home > Back-end >  Print data from Class instance
Print data from Class instance

Time:05-05

I want to print out data from a Class instance. I tried including data in str function, but this only works when value is at its default (an empty list). After I've added data to the list, I can only get memory objects printed. Can anyone help me troubleshoot why this is happening? I want to be able to print out objects to use in debugging.

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)
        else:
            pass
    
    def __str__(self):
        return str(self.grades)

pieter=Student("Pieter Bruegel the Elder", 8)

print(pieter)
[]  # Returns empty list of grades as it was initiated. 

class Grade():
    minimum_passing=65
    
    def __init__(self,score):
        self.score=score
    
    def is_passing(self):
        if self.score >= self.minimum_passing:
            return True
        else:
            return False

pieter.add_grade(Grade(100))
pieter.add_grade(Grade(40))

print(pieter)
[<__main__.Grade object at 0x000002B354BF16A0>, <__main__.Grade object at 0x000002B354BF13A0>]

CodePudding user response:

When you tell it to print 'pieter', you are telling it to attempt to print the object. What you need to do is add a print function in the class or use the specific variable in the object. Try adding something like this:

def print_object(self):
    print("The name is: {self.name}")
    print("The year is: {self.year}")
    print("The grades are: {self.grades}")

If you have any questions, please feel free to reach out.

CodePudding user response:

The list.__str__() method uses repr() to get the representation of the list elements. So this is showing the repr() of all the Grade objects in the grades list. Since Grade doesn't have a custom __repr__() method, you get the default representation.

You could define Grade.__repr__() to specify how you want grades to appear, or you could change the Student.__str__() method to get the scores from the Grade objects in the list.

class Student():
    
    def __init__(self,name,year):
        self.name=name
        self.year=year
        self.grades=[]
    
    def add_grade(self, grade):
        if isinstance(grade, Grade):
            self.grades.append(grade)
        else:
            pass
    
    def __str__(self):
        return str([str(g) for g in self.grades])

CodePudding user response:

The problem is that Grade itself doesn't have a neat representation as a string. Thus the str(self.grades) call can only print a list of abstract instance data. You could include a representation:

class Grade():

    # the other stuff goes here...

    def __repr__(self):
        return f'Grade({self.score}'

Now print(pieter) prints:

[Grade(100), Grade(40)]

However, I wouldn't use the __str__() magic method to print the grades. It's clearer to define an explicit method such as print_grades() for this purpose.

  • Related