Python Dates and Times in Python 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
Chris Freeman
Treehouse Moderator 59,892 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!