Exercises
The __str__ Method
3 tasks. Write the code, press Check, and the page runs it against a real Python interpreter.
Exercise 1Passed
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))__str__ takes self and returns a string.
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"{self.name}, aged {self.age}"
print(Dog("Rex", 3))Exercise 2Passed
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")])Containers use __repr__, not __str__.
class Dog:
def __init__(self, name):
self.name = name
def __repr__(self):
return f"Dog({self.name!r})"
print([Dog("Rex")])Exercise 3Passed
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([])))__len__ returns an integer, and bool() falls back to it.
class Basket:
def __init__(self, items):
self.items = items
def __len__(self):
return len(self.items)
print(len(Basket(["a", "b"])))
print(bool(Basket([])))