Classes (class)
A class is a blueprint that bundles data and functions; each object you create from it is an instance.
Used in 53 lessons of the course, from 00.07.
You write class Price: and, indented below it, the class body. The name uses CamelCase by convention, so you can tell it apart from a function.
Inside, you define methods with def. The special method __init__ runs when the object is created and stores its data on self. To create an instance, you call the class like a function: Price(10).
Why use classes? Because they keep data and the behavior that belongs to it together. That way each price knows how to format itself.
In the course you'll see classes everywhere: Pydantic models, tools and states are declared with class. Often they inherit from another class, like class Price(BaseModel):, and only declare fields. Reading class as "a new kind of object is defined here" helps you understand those lines.
Reach for it when: several pieces of data always travel together and you want functions that work on them, or when a library asks you to define a model by inheriting from its class.
Examples
Common mistake
class Price:
def __init__(self, amount):
self.amount = amount
def label():
return "price"
print(Price(5).label())Why: Python passes the instance as the first argument to every method. If the method doesn't declare `self`, it gets an argument it didn't expect.
How to write it: Always write self as the first parameter: def label(self):.
Common mistake
class Price:
def __init__(self, amount):
self.amount = amount
p = Price
print(p)Why: Without parentheses you don't create an instance; you only give the class itself another name.
How to write it: Call the class with its arguments: p = Price(10).
