Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Dates and Times in Python (2014) Let's Build a Timed Quiz App The Quiz Class

Eric Luhta
Eric Luhta
6,357 Points

Overriding __str__ to see question list

When the Quiz class' question list was printed in the terminal, it returns the standard <questions.Multiply object at etc> for each item. Out of curiosity I tried overriding the Add and Multiply str methods to see if I could get it to list the text instead. Here is my code but I am not sure what is wrong since it still lists the default object at memory location when I exit and retry. Thanks!

class Add(Question):

    def __init__(self, num1, num2):
        self.text = '{} + {}'.format(num1, num2)
        self.answer = num1 + num2

    def __str__(self):
        return 'Add {}'.format(self.text)

[MOD: added ```python formatting -cf]

1 Answer

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,441 Points

The issues is context. When you invoke an object, the default interpretation is the __repr__ which usually is a *repr*esentation of the object. If __repr__ isn't defined, you get a pointer to the object memory location.

Your code is fine. You need to look at your object in a string context. If you were to print() your object or wrap it in str(), you would see what you seek.

>>> class Math():
...     def __init__(self, num1, num2):
...         self.text = '{} + {}'.format(num1, num2)
...         self.answer = num1 + num2
...     d ef __str__(self):
...         return 'Add {}'.format(self.text)
... 
>>> m1 = Math(4, 5)
>>> m1  # returns __rep__
<__main__.Math object at 0x7fe471df2278>
>>> m1.__repr__()    # returns __rep__
'<__main__.Math object at 0x7fe471df2278>'
>>> m1.__str__() # runs __str__ method
'Add 4 + 5'
>>> str(m1)  # runs __str__ method 
'Add 4 + 5'
>>> print(m1)   # runs __str__ method 
Add 4 + 5
Eric Luhta
Eric Luhta
6,357 Points

Got it, thanks for the great explanation!