Learn: Classes and objects¶
Five short tutorials that take you from defining your first class through to writing code that feels at home alongside Python's built-in types. Each one is a Jupyter notebook — read it in the browser, and edit and run any code cell directly on the page.
The tutorials build on each other, so working through them in order is the fastest path. Each takes roughly fifteen to twenty minutes.
The sequence¶
- Classes, instances, and
__init__— defining a class, whatselfis, attributes versus methods. - Dunder methods —
__repr__,__eq__, ordering,__str__,__hash__, and what makes a class feel Pythonic. - Data classes —
@dataclass,field,frozen,slots, plusNamedTupleandTypedDictas lighter alternatives. - Inheritance and composition —
super(), the MRO, and when to favour composition. - Class attributes, properties, classmethods, and staticmethods — the supporting cast that rounds out a class definition.
Before you start¶
You'll get more from these if you're already comfortable with Python functions (parameters, return values, default arguments) and data structures (lists and dictionaries). Classes build on both.
You don't need Python installed locally — every tutorial runs in your browser. If you'd rather run them on your own machine, each notebook has a download button in the top-right corner.