Printing objects
Python · Unit 12: Classes and objects
- Full plan
- Python
- 10 exercises
If you print an object of yours, Python doesn't know what to show: you get something like <__main__.Pet object at 0x7f3a…>, its type and a memory number that changes every time.
If the class has a __str__ method that returns a string, print shows that string.
class Pet:
def __init__(self, name):
self.name = name
def __str__(self):
return "I'm " + self.name
luna = Pet("Luna")
print(luna)Prints
I'm Luna
The rest of the explanation is in the lesson, which is part of the full plan.
Exercises in this lesson
You do them in the app, which checks them on the spot and explains why.
1. Multiple choice
The
Bookclass has no__str__. What comes out withprint(book)?2. Predict the output
What does this code print?
3. Complete the code
Complete it so it prints: 10 coins
4. Find the bug
This program should print 5 km. Which line has the error?
5. Complete the code
Complete it so it prints: Table 4
6. Predict the output
What does this code print?
7. Predict the output
What does this code print?
8. Multiple choice
If a class has
__repr__but no__str__, what doesprintshow for one of its objects?9. Find the bug
This program should print [Tile(4), Tile(9)]. Which line has the error?
10. Predict the output
What does this code print?
It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.