Skip to the content

Printing objects

Python · Unit 12: Classes and objects

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. 1. Multiple choice

    The Book class has no __str__. What comes out with print(book)?

  2. 2. Predict the output

    What does this code print?

  3. 3. Complete the code

    Complete it so it prints: 10 coins

  4. 4. Find the bug

    This program should print 5 km. Which line has the error?

  5. 5. Complete the code

    Complete it so it prints: Table 4

  6. 6. Predict the output

    What does this code print?

  7. 7. Predict the output

    What does this code print?

  8. 8. Multiple choice

    If a class has __repr__ but no __str__, what does print show for one of its objects?

  9. 9. Find the bug

    This program should print [Tile(4), Tile(9)]. Which line has the error?

  10. 10. Predict the output

    What does this code print?

Do this lesson

It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.

See all lessons →