Chapters
Python114 chapters

Exercises

The __init__ Method

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

Exercise 1

Give Dog an __init__ taking name and age, then print both for Rex aged 3.

Python
class Dog:
    pass

rex = Dog("Rex", 3)
print(rex.name, rex.age)
Exercise 2

Fix the shared list so each dog gets its own tricks.

Python
class Dog:
    tricks = []

    def __init__(self, name):
        self.name = name

rex = Dog("Rex")
fido = Dog("Fido")
rex.tricks.append("sit")
print(fido.tricks)
Exercise 3

Reject an empty name with a ValueError so an invalid dog can never exist.

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

try:
    Dog("")
    print("no error")
except ValueError as problem:
    print("ValueError:", problem)