Free lab Real Python 3. Zero installs. Your code stays in this browser. Open the playground

Classes & Objects

18 min 35 XP
Study loop Read Predict Run Tweak Prove Review
Lesson 4 of 6 · View course roadmap
Step 1

Learn the idea

A class is a blueprint; an object (instance) is a thing built from it. Classes bundle data (attributes) with behaviour (methods):

  • __init__ — the constructor, runs when you create an instance
  • self — the instance itself; every method receives it first
  • self.name = name — stores data on the instance

Think of Dog as the cookie cutter and each Dog("Rex") as a cookie. Classes shine when data and the functions that operate on it belong together — a bank account with balance + deposit/withdraw, a player with health + damage logic.

Where you'll use this

Django models, game entities, GUI widgets, bank accounts — anywhere data and behaviour travel together, there's a class. Frameworks hand you base classes and your entire job is filling in methods.

Common mistakes

  • Forgetting self in the method signature → 'takes 0 positional arguments but 1 was given', the most-googled Python error.
  • Writing name = name instead of self.name = name in __init__ — the data vanishes when the method ends.
  • Class-level mutable attributes shared by every instance — define per-instance data inside __init__, not in the class body.

Pro tip

For data-carrying classes, @dataclass writes __init__, __repr__ and __eq__ for you: @dataclass class Point: x: int; y: int. Modern Python uses it constantly.

Step 2

Watch how it runs — line by line


        

Press play to watch Python execute this code, one line at a time.

Step 3

Try it yourself

Blank · autosaved

The lesson example is loaded and ready — press Run, then change something and run it again. Breaking it is part of learning. Want a clean slate? Tap “New blank”.

PYexample.py
+ Enter to run
Output appears here…
Step 4

Pass the challenge +35 XP

Blank · autosaved

Create a class BankAccount with __init__(self, owner) starting balance 0, a deposit(amount) method, and a report() method returning "{owner}: {balance}". Create an account for "Simas", deposit 50 then 25, and print the report.

Target output
Simas: 75
PYchallenge.py
Run your code to check it…
Step 5

Check your understanding

1. What is self in a method?
2. When does __init__ run?
Last step

Your notes (saved on this device)

Tip: use and to move between lessons, K to search everything.

Your next ten minutes

Write Python that does something useful.

Start free. No install, no card, no passive video marathon.

Start learning free → Explore the path