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.
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.selfis "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:
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 doneStep 1 of 2 · A bank account
Complete the BankAccount class:
__init__(self, owner)stores the owner and startsbalanceat0deposit(self, amount)adds to the balancewithdraw(self, amount)subtracts, but raisesValueError("Insufficient funds")if there isn't enough
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.
Step 2 of 2 · A nice printout
Add a __str__ method to Book so that print(book) shows Clean Code by Robert Martin.
class Book:
def __init__(self, title, author):
self.title = title
self.author = author
print(Book("Clean Code", "Robert Martin"))
Output appears here. Press Run or Ctrl/⌘ + Enter.
✅ Check your understanding
What is self?
What's the difference between a class and an object?
Create a free account to track your progress.