Chapters
Python114 chapters

Exercises

Methods

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

Exercise 1

Add learn and show methods so the dog can collect tricks.

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

rex = Dog("Rex")
rex.learn("sit")
rex.learn("roll")
print(rex.show())
Exercise 2

Make area a property so it recalculates when width changes.

Python
class Rectangle:
    def __init__(self, width, height):
        self.width = width
        self.height = height
        self.area = width * height

r = Rectangle(3, 4)
print(r.area)
r.width = 10
print(r.area)
Exercise 3

Add a classmethod called puppy that builds a Dog aged 0.

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

rex = Dog.puppy("Rex")
print(rex.name, rex.age)