Python/Classes & structure 9 min

Classes and objects

Bundle data with the behaviour that belongs to it.

classselfrepr

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.

python · editable
loading editor…

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.

python · editable
loading editor…

Reach for a class when data and behaviour travel together. A plain dict or function is often the better answer for one-off transformations.

practice this