~/learn/Python · Classes & structure
Classes and objects
Bundle data with the behaviour that belongs to it.
why this matters
Once a script grows past a few hundred lines, grouping data with the functions that act on it is what keeps it readable.
A class defines a type. __init__ runs when you create an instance and stores its state on self; methods are functions that take self as the first parameter.
Try it: Add a discount(pct) method returning the discounted revenue.
__repr__ decides how the object prints, which makes debugging far easier. Other dunder methods let your objects work with len(), ==, sorting and iteration.
Note
Reach for a class when data and behaviour travel together. A plain dict or function is often the better answer for one-off transformations.
Anatomy of a class
class Account:
def __init__(self, owner): ← runs on creation
self.owner = owner ← data on the instance
def deposit(self, amount): ← behaviourCommon gotcha
Every method needs self as its first parameter, and you use self.x to reach the instance's own data.
key takeaways
- __init__ sets up a new instance.
- self refers to the instance being worked on.
- Methods are functions that live on the class.
check your understanding
What does __init__ do?
free practice
Build confidence with a question you can solve without Pro.