Lesson 6 of 7 · 12 min · 2 hands-on steps

Classes & Objects

Bundle data and behavior together. The foundation of object-oriented programming.

A class is a blueprint

A class describes a kind of thing: what data it has and what it can do. Objects are the actual things made from it.

Python · try it
class Dog:
    def __init__(self, name, age):
        self.name = name    # data (attributes)
        self.age = age

    def bark(self):         # behavior (methods)
        return f"{self.name} says woof!"

rex = Dog("Rex", 3)
luna = Dog("Luna", 5)
print(rex.bark())
print(luna.name, luna.age)
  • __init__ runs when you create an object. It sets up the data.
  • self is "this particular object", so Rex and Luna each keep their own name.

Watch objects get built

Why classes matter for your career

Most large codebases (and many interview questions) are organized around classes: User, Order, ShoppingCart, PaymentProcessor. The idea of keeping data and the code that changes it together is called encapsulation. It's the first pillar of object-oriented programming, which you'll go deeper into in the OOP & Clean Code course.

Special methods

Methods with double underscores let your objects work with Python's built-in features:

Python · try it
class Money:
    def __init__(self, cents):
        self.cents = cents

    def __str__(self):
        return f"${self.cents / 100:.2f}"

    def __add__(self, other):
        return Money(self.cents + other.cents)

print(Money(250) + Money(199))

🧪 Practice: 2 steps

0 / 2 done

Step 1 of 2 · A bank account

Complete the BankAccount class:

  • __init__(self, owner) stores the owner and starts balance at 0
  • deposit(self, amount) adds to the balance
  • withdraw(self, amount) subtracts, but raises ValueError("Insufficient funds") if there isn't enough
Python
class BankAccount:
    def __init__(self, owner):
        pass

    def deposit(self, amount):
        pass

    def withdraw(self, amount):
        pass

Output appears here. Press Run or Ctrl/⌘ + Enter.

✅ Check your understanding

  1. What is self?

  2. What's the difference between a class and an object?

Create a free account to track your progress.