Chapters
Python114 chapters

Exercises

Dataclasses

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

Exercise 1

Turn Dog into a dataclass so it prints usefully and compares by value.

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

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

Give each dog its own tricks list.

Python
from dataclasses import dataclass

@dataclass
class Dog:
    name: str
    tricks: list = None

rex = Dog("Rex")
print(rex.tricks)
Exercise 3

Make Point immutable so it can be a dictionary key.

Python
from dataclasses import dataclass

@dataclass
class Point:
    x: int
    y: int

print({Point(1, 2): "here"}[Point(1, 2)])