Learn to Code
All tracks
Learn to Code

Free lessons from scratch to pro — every language, databases and DevOps.

AboutContactPrivacy PolicyTerms of Use

Your progress is saved in this browser. © 2026 Learn to Code

PY
Python
0/14 completed
Beginner
Hello PythonVariables and typesWorking with stringsConditions and loopsFunctions
Intermediate
Lists, tuples, dicts and setsFiles and exceptionsModules and the standard library
Advanced
Classes and OOPIterators and generatorsDecorators and context managers
Pro
Async PythonTesting and type hintsVirtual environments, packages and real projects
Tracks / Python / Advanced

Classes and OOP

Object-oriented programming (OOP) bundles data and the functions that work on it into objects. A class is the blueprint; an object (or instance) is a thing built from it. You've been using objects all along: every string, list and dict is one.

Your first class

Python · editable
  • __init__ is the initialiser. It sets up each new object.
  • self is the object the method is working on. Python passes it automatically: rex.add_trick("sit") calls Dog.add_trick(rex, "sit").
  • Each object has its own attributes: Rex's tricks aren't Bella's.

Class attributes and special methods

Python · editable

Methods with double underscores ("dunder" methods) hook your class into Python's syntax: len(), +, ==, for loops, print… That's how your own classes can feel built-in.

Encapsulation and properties

By convention, a leading underscore means "internal, don't touch from outside". A @property looks like an attribute but runs code, which is perfect for validation and computed values:

Python · editable

Inheritance

A class can inherit from another, reusing its code and adding or changing behaviour:

Python · editable

Calling the same method on different types and getting type-specific behaviour is called polymorphism.

💡 Prefer composition ("has a") over deep inheritance ("is a") trees. A Car has an Engine; it isn't one. Short, shallow hierarchies are easier to change.

Dataclasses: less boilerplate

For classes that mainly hold data, @dataclass writes __init__, __repr__ and __eq__ for you:

Python · editable

Class methods and static methods

Python · editable

Pattern matching on objects

match works with classes, which makes handling different object types elegant:

Python · editable

Practice

  1. Create a Rectangle dataclass with width and height, plus area and perimeter properties, and an is_square() method.
  2. Write a ShoppingCart class with add(product, qty), remove(product) and total(), using the Product dataclass above.
  3. Give ShoppingCart a __len__ method (number of items) and a __str__ that lists the contents.
Python · editable
✎ Check your understanding

1.What is self in a method?

2.Which method makes print(obj) show something friendly?

3.What does @dataclass generate for you?

← Modules and the standard library