Printing an object shows something unhelpful by default:
class Book:
def __init__(self, title, author):
self.title = title
self.author = author
book = Book("Emma", "Austen")
print(book)
Output:
<__main__.Book object at 0x7f3a2c1d4e80>
Defining a method named __str__ fixes this. It returns the string that print (and str) should use for the object:
class Book:
def __init__(self, title, author):
self.title = title
self.author = author
def __str__(self):
return f"{self.title} by {self.author}"
book = Book("Emma", "Austen")
print(book)
Output:
Emma by Austen
Names with double underscores on both sides, like __init__ and __str__, are hooks Python calls for you: __init__ at creation, __str__ when a string form is needed. You define them; Python decides when to call them.
Receipt whose __init__ takes item and total and stores both.__str__ method that returns exactly:Receipt: <item>, <total> AUD
print(Receipt("notebook", 45)) prints Receipt: notebook, 45 AUD.
Run your code to see the output, then press Submit.
import unittest
class TestReceiptStr(unittest.TestCase):
def test_str_form(self):
self.assertEqual(str(Receipt("notebook", 45)), "Receipt: notebook, 45 AUD")
def test_str_uses_the_object_attributes(self):
self.assertEqual(str(Receipt("pen", 12)), "Receipt: pen, 12 AUD")
class Receipt:
def __init__(self, item, total):
self.item = item
self.total = total
def __str__(self):
return f"Receipt: {self.item}, {self.total} AUD"
print(Receipt("notebook", 45))
Sign in to join the discussion.
No comments yet. Be the first to ask a question.
Press Run to execute your code, or Submit to test and complete this problem.