Class fields with defaults
Inside a class, `name: type = value` declares a field and the value it has if nobody gives another.
Used in 26 lessons of the course, from 01.04.
A field is a piece of data that each object of the class keeps. You write it in the class body with a type hint and, optionally, a default value: title: str = "Untitled".
Read it like this: the field title is a str and is "Untitled" unless you say otherwise.
In a dataclass, or a pydantic model, that line also lets you pass the field as a keyword argument when you create the object. If you leave it out, the default is used.
In the course you will see title: str = Field(description="..."). There the value on the right is not plain text: it is a Field object that stores extra information about the field, such as its description. The field carries its own documentation.
class Event:
title: str = "Untitled"
Without something that processes the class (like @dataclass), this only creates a class attribute.
Reach for it when: an object has data with a sensible starting value, or when you want to describe each field with its type.
Examples
Common mistake
from dataclasses import dataclass
@dataclass
class Basket:
items: list = []Why: A list as a default would be shared by every object, so dataclass forbids it.
How to write it: Use field(default_factory=list) so each object gets its own list.
Common mistake
class Event:
title: str = "Untitled"
e = Event(title="Launch")Why: A plain class does not turn fields into `__init__` parameters.
How to write it: Add @dataclass above the class (or inherit from BaseModel in pydantic).
