Learn/Python/10. Structuring data with classes
Lesson 10 of 15
Sign in

Python, lesson 10

Structuring data with classes

A dictionary like {"name": "Rex", "hunger": 3} works for quick jobs, but as a program grows you want something sturdier: a type with a fixed set of fields and the operations that belong to it. That's what a class is. A class is a blueprint; each instance (object) made from it has its own data.

A first class

  • __init__ runs automatically when you create an instance with Rectangle(3, 4). Its job is to set up the starting data.
  • self is the instance being worked on. Python passes it for you: box.area() is really Rectangle.area(box).
  • self.width = width creates an , a variable that lives on the object.

2 exercises to try what you just read.

Exercise 1

Garden plots

Press Ctrl Enter or Check to test your code.

Exercise 2

Virtual pet

Press Ctrl Enter or Check to test your code.

attribute
  • Functions defined in a class are methods. They read and change the object through self.
  • Each object keeps its own attributes, so two rectangles never get mixed up.

    Keep mutable data per instance

    Create lists and dictionaries inside __init__, not directly in the class body. A list written in the class body is shared by every instance, which leads to baffling bugs where adding to one object's list changes them all.

    Printing objects nicely

    Print an object and you get something like <__main__.Rectangle object at 0x...>. Define __str__ to control what print() and f-strings show:

    Methods with double underscores on both sides are called special methods. Python calls them for you at the right moment: __init__ on creation, __str__ on printing, __eq__ for ==, and many more.

    Dataclasses

    Many classes are mostly data. Writing __init__, a readable representation and == by hand for those is repetitive, so the standard library's dataclasses module writes them for you. You list the fields with type hints:

    Fields with defaults must come after fields without them. For a mutable default such as a list, use field(default_factory=list) so every instance gets a fresh one.

    Pass frozen=True to make instances read-only, which is good for values that should never change, like a coordinate. Pass order=True to make instances sortable by their fields in order.

    You can still add your own methods to a dataclass exactly as you would to a normal class.

    When to use what

    • A plain tuple or dict for a quick, local group of values.
    • A dataclass when the data has a clear shape and gets passed around.
    • A full class when the object has behaviour and rules to protect, like a bank account that must never go negative.

    Further reading

    • The Python Tutorial: Classes
    • dataclasses module
    • Data model: special method names

    Finish the Plot class. area() returns width × length, fence() returns the perimeter, and is_square() returns whether both sides are equal. Each input line holds a width and a length (whole numbers). The starter prints one line per plot in this form:

    Sample input:

    Sample output:

    Make a @dataclass called Pet with fields name: str, hunger: int = 5 and mood: int = 5. Add three methods:

    • feed() lowers hunger by 3
    • play() raises mood by 2 and raises hunger by 1
    • nap() raises mood by 1

    Neither value may go below 0 or above 10: clamp it after every change. Add __str__ returning <name>: hunger <hunger>, mood <mood>.

    The first input line is the pet's name. Each following line is a command (feed, play or nap). The starter runs the commands and prints the pet at the end.

    Sample input:

    Sample output:

    class Rectangle:
        def __init__(self, width, height):
            self.width = width
            self.height = height
    
        def area(self):
            return self.width * self.height
    
    
    box = Rectangle(3, 4)
    print(box.area())     # 12
    print(box.width)      # 3
    class Playlist:
        def __init__(self, name):
            self.name = name
            self.songs = []          # each playlist gets its own list
        def __str__(self):
            return f"{self.width}x{self.height} rectangle"
    from dataclasses import dataclass, field
    
    @dataclass
    class Book:
        title: str
        pages: int
        read: bool = False
        tags: list[str] = field(default_factory=list)
    
    b = Book("Dune", 412)
    print(b)                       # Book(title='Dune', pages=412, read=False, tags=[])
    print(b == Book("Dune", 412))  # True: compares field by field
    area=12 fence=14 square=False
    3 4
    5 5
    area=12 fence=14 square=False
    area=25 fence=20 square=True
    Biscuit
    play
    play
    feed
    Biscuit: hunger 4, mood 9