Chapters
Python114 chapters

Exercises

The __str__ Method

3 tasks. Write the code, press Check, and the page runs it against a real Python interpreter.

Exercise 1

Give Dog a __str__ so printing it shows the name and age.

Python
class Dog:
    def __init__(self, name, age):
        self.name = name
        self.age = age

print(Dog("Rex", 3))
Exercise 2

Add a __repr__ so a list of dogs prints usefully too.

Python
class Dog:
    def __init__(self, name):
        self.name = name

    def __str__(self):
        return self.name

print([Dog("Rex")])
Exercise 3

Give Basket a length so len() works and an empty basket is falsy.

Python
class Basket:
    def __init__(self, items):
        self.items = items

print(len(Basket(["a", "b"])))
print(bool(Basket([])))