🐍 Python for Everyone

← Back to all chapters

Chapter 14 of 27 Intermediate 55 min read

OOP Basics

Every program so far has kept related data in separate variables, or loose dictionaries, and passed them around to separate functions that operate on them. That works, but it gets fragile fast — nothing stops a function meant for one dictionary shape from being called on a completely different one. A class is Python's way of bundling data and the behavior that belongs with it into a single, reusable blueprint. This chapter is about building your first classes from scratch.

How to read this chapter

Picture a program tracking bank accounts using nothing but variables: alice_balance, alice_owner, bob_balance, bob_owner — and a separate withdraw(balance, amount) function that has no idea whose balance it's even touching. Now picture ten thousand customers. That's the exact problem classes exist to solve — one blueprint, BankAccount, that keeps an account's data and the actions it supports bundled together as one thing.
Sub-topic 1 of 6

1. Classes & objects

At a glance
  • A class is a blueprint that describes what data and behavior something should have.
  • An object (also called an instance) is one actual thing built from that blueprint.
  • Every value used so far — strings, lists, dictionaries — is already an object built from a class Python provides; this chapter is about writing your own.
Why this matters: a dictionary like {"owner": "Alice", "balance": 100} stores data, but nothing stops a typo like row["blance"] from silently creating a new key instead of raising an error, and there's no way to attach a withdraw() action directly to it. A class fixes both problems at once.
What is... a class? A class is a blueprint — a definition of what data a thing has and what it can do — but it isn't a thing by itself, the same way a cookie cutter isn't a cookie. Nothing exists yet just because a class is defined.

A minimal class needs only the class keyword and a name, written in CapitalizedWords by convention:

minimal_class.py
class BankAccount:
    pass

print(BankAccount)
print(type(BankAccount))
actual output of minimal_class.py
<class '__main__.BankAccount'>
<class 'type'>

BankAccount by itself is just the blueprint — no account exists yet. Calling the class like a function creates an object, a real instance built from that blueprint:

What is... an object (or instance)? An object is one actual thing created from a class — the cookie, not the cutter. A program can create many separate objects from the same class, each one independent of the others.
first_object.py
class BankAccount:
    pass

acct = BankAccount()
print(acct)
print(type(acct))
actual output of first_object.py — a real BankAccount object now exists in memory
<__main__.BankAccount object at 0x7f2a1c0d4d90>
<class '__main__.BankAccount'>

That 0x7f2a... is just a memory address — proof this really is one specific object, distinct from any other BankAccount that gets created later. It looks messy because this class hasn't told Python how to describe itself yet; Sub-topic 5 fixes that.

This isn't a brand-new idea, either — every value used since Chapter 1 has secretly been an object of some built-in class:

everything_is_an_object.py
print(type("hello"))
print(type(42))
print(type([1, 2, 3]))
print(type({"a": 1}))
actual output of everything_is_an_object.py
<class 'str'>
<class 'int'>
<class 'list'>
<class 'dict'>

str, int, list, and dict are all classes Python already provides — a string is an object built from the str blueprint, the same relationship acct has with BankAccount above. Writing a custom class just means designing a new blueprint for a shape of data Python doesn't already provide out of the box.

try_it.py
Click "Run Code" — try creating a third object and comparing it too.
Go Deeper: why loose dicts and functions eventually break down

A dictionary shape like {"owner": ..., "balance": ...} only exists by convention — nothing enforces that every account dictionary in a program actually has both keys spelled correctly, and nothing ties a withdraw() function to that shape specifically. A class makes the shape and its behavior part of one definition, so every object built from it is guaranteed to have the same structure.

Quick recap
  • A class is a blueprint; it doesn't exist as a "thing" by itself.
  • An object (instance) is one real thing created from a class, using ClassName().
  • Every value in Python — strings, lists, dicts, and now custom classes — is an object of some class.
Sub-topic 2 of 6

2. The __init__ method & instance attributes

At a glance
  • __init__ is a special method that runs automatically every time a new object is created.
  • self refers to the specific object being created or acted on — it's always the first parameter.
  • self.name = value creates an instance attribute — data that belongs to that one object only.
Why this matters: an empty BankAccount() from Sub-topic 1 has no owner and no balance — __init__ is how a class fills in an object's starting data the moment it's created.

__init__ ("dunder init," short for the double underscores on each side) is defined like any other function, but Python calls it automatically whenever ClassName(...) runs:

init_demo.py
class BankAccount:
    def __init__(self, owner, balance):
        self.owner = owner
        self.balance = balance

acct1 = BankAccount("Alice", 100)
acct2 = BankAccount("Bob", 250)

print(acct1.owner, acct1.balance)
print(acct2.owner, acct2.balance)
actual output of init_demo.py
Alice 100
Bob 250
What is... __init__? __init__ is the constructor — a method Python runs automatically right after a new object is created, used to set up that object's starting data. BankAccount("Alice", 100) creates the object and immediately calls __init__(self, "Alice", 100) on it.

Notice self is never actually passed in when calling BankAccount("Alice", 100) — only two arguments are given, yet __init__ lists three parameters.

What is... self? self is how a method refers to the specific object it's working on. Python fills it in automatically — it's the object itself, supplied behind the scenes, so a call site never writes it explicitly. Every method defined inside a class lists self as its first parameter for this reason.

self.owner = owner is where the real work happens — it creates an instance attribute called owner, attached to that one specific object:

What is... an instance attribute? An instance attribute is a piece of data that belongs to one specific object, set with self.name = value inside a method (almost always __init__). Two objects from the same class each get their own independent copy.

Tracing acct1 and acct2 side by side shows exactly how independent they are — changing one never touches the other:

acct1 and acct2 — two separate objects, two separate sets of attributes
acct1  ->  owner = "Alice"   balance = 100
acct2  ->  owner = "Bob"     balance = 250

This is the core benefit over a loose dictionary: acct1 and acct2 are guaranteed to have the exact same attributes (owner and balance), because both were built from the same __init__ — there's no way to accidentally create one with a typo'd attribute name that the rest of the program doesn't expect.

Go Deeper: __init__ can take default values too

__init__ is an ordinary function underneath, so Chapter 3's default-argument syntax still works: def __init__(self, owner, balance=0): lets BankAccount("Alice") create an account that starts at a balance of 0 without requiring a second argument every time.

Quick recap
  • __init__ runs automatically when ClassName(...) creates a new object.
  • self is the object itself, filled in automatically as the first parameter of every method.
  • self.name = value creates an instance attribute — data unique to that one object.
Sub-topic 3 of 6

3. Instance methods

At a glance
  • An instance method is a function defined inside a class that operates on one object's own data via self.
  • self is always the first parameter, exactly like in __init__ — it's how the method knows which object's data to use.
  • Calling acct.deposit(50) automatically passes acct in as self; nothing extra is written at the call site.
Use this when: an action naturally belongs to one specific object's data — depositing into one account, not "deposit in general."

BankAccount can only store data so far. An instance method adds behavior that reads and changes an object's own attributes:

instance_method_demo.py
class BankAccount:
    def __init__(self, owner, balance):
        self.owner = owner
        self.balance = balance

    def deposit(self, amount):
        self.balance += amount

    def withdraw(self, amount):
        if amount > self.balance:
            print("Insufficient funds.")
            return
        self.balance -= amount

acct = BankAccount("Alice", 100)
acct.deposit(50)
print(acct.balance)
acct.withdraw(30)
print(acct.balance)
acct.withdraw(1000)
print(acct.balance)
actual output of instance_method_demo.py
150
120
Insufficient funds.
120
What is... an instance method? An instance method is a function defined inside a class that takes self as its first parameter, letting it read and modify that specific object's attributes. deposit and withdraw above are both instance methods of BankAccount.

acct.deposit(50) only supplies one argument, 50, at the call site — yet deposit is defined with two parameters, self and amount. Python fills self in as acct automatically, the same rule __init__ already followed in Sub-topic 2. This is exactly why self is always written first: it's a fixed convention every method follows, not something decided case by case.

Every reference to self.balance inside deposit and withdraw means "this particular account's balance" — never any other account's. Two separate BankAccount objects calling .deposit() never interfere with each other:

independent_methods_demo.py
acct1 = BankAccount("Alice", 100)
acct2 = BankAccount("Bob", 250)

acct1.deposit(20)
acct2.withdraw(50)

print(acct1.owner, acct1.balance)
print(acct2.owner, acct2.balance)
actual output of independent_methods_demo.py
Alice 120
Bob 200
try_it.py
Click "Run Code" — try calling acct.deposit() a second time.
Go Deeper: forgetting self is a common, very real mistake

Leaving self off a method definition — writing def deposit(amount): instead of def deposit(self, amount): — causes a confusing TypeError the moment the method is called, because Python still tries to pass the object in as the first argument automatically. This is one of the single most common beginner mistakes with classes; Task 7 in this chapter's exercises works through exactly this bug.

Quick recap
  • An instance method is a function inside a class that takes self as its first parameter.
  • self refers to whichever object the method was called on — filled in automatically, never written at the call site.
  • Each object's instance methods only ever touch that object's own attributes.
Sub-topic 4 of 6

4. Class attributes vs. instance attributes

At a glance
  • A class attribute is defined directly inside the class body (not inside __init__) and is shared by every instance.
  • An instance attribute (from Sub-topic 2) belongs to one object only.
  • A mutable class attribute, like a list, is especially dangerous — every instance shares the exact same list object.
Why this matters: this is the same trap as Chapter 10's mutable default argument, wearing a different disguise — shared mutable state causing changes to leak between places that should be independent.

A class attribute is written once, inside the class body, outside any method — every object built from the class sees the same value unless something overrides it:

class_attribute_demo.py
class Employee:
    company_name = "Acme Corp"

    def __init__(self, name, salary):
        self.name = name
        self.salary = salary

emp1 = Employee("Alice", 60000)
emp2 = Employee("Bob", 55000)

print(emp1.company_name, emp1.name, emp1.salary)
print(emp2.company_name, emp2.name, emp2.salary)
actual output of class_attribute_demo.py
Acme Corp Alice 60000
Acme Corp Bob 55000
What is... a class attribute? A class attribute is a value defined directly in the class body, not inside __init__, shared by every instance of that class instead of being copied per object. company_name above belongs to the Employee class itself.

Changing it on the class updates it everywhere at once — every existing object immediately sees the new value, since they were never given their own separate copy:

class_attribute_shared_change.py
Employee.company_name = "Acme Corporation"
print(emp1.company_name)
print(emp2.company_name)
actual output of class_attribute_shared_change.py
Acme Corporation
Acme Corporation

That sharing is exactly the point for something genuinely common to every instance, like a company name. It becomes a serious bug, though, the moment the shared value is mutable — something that can be changed in place, like a list.

ShoppingCart with items as a class attribute — the bug, traced instance by instance
class ShoppingCart:
    items = []   # <- BUG: one list, shared by every instance

    def __init__(self, owner):
        self.owner = owner

    def add_item(self, item):
        self.items.append(item)

cart1 = ShoppingCart("Alice")
cart2 = ShoppingCart("Bob")

cart1.add_item("Book")
cart2.add_item("Headphones")

cart1.owner -> "Alice"   cart1.items -> ['Book', 'Headphones']
cart2.owner -> "Bob"     cart2.items -> ['Book', 'Headphones']
                                         ^^^^^^^^^^^^^^^^^^^^^
                                         both carts see BOTH items

cart2 never called add_item("Book"), yet "Book" shows up in its cart too — because cart1.items and cart2.items are, secretly, the exact same list object in memory. .append() mutates that one shared list, and every instance looks at it and sees the change.

What is... the mutable class attribute trap? Defining a mutable value like items = [] directly in the class body makes every instance share that one object — a change made through any single instance is visible through all of them. This is the exact same failure mode as Chapter 10's mutable default argument, just triggered by a class body instead of a function signature.

The fix is the same instinct Chapter 10 already taught: give each object its own fresh list inside __init__, as an instance attribute, instead of sharing one at the class level:

shopping_cart_fixed.py
class ShoppingCart:
    def __init__(self, owner):
        self.owner = owner
        self.items = []  # FIX: each instance gets its own empty list

    def add_item(self, item):
        self.items.append(item)

cart1 = ShoppingCart("Alice")
cart2 = ShoppingCart("Bob")

cart1.add_item("Book")
cart2.add_item("Headphones")

print(cart1.owner, "->", cart1.items)
print(cart2.owner, "->", cart2.items)
actual output of shopping_cart_fixed.py — now genuinely independent
Alice -> ['Book']
Bob -> ['Headphones']

The rule to carry forward: class attributes are for values that are genuinely meant to be identical across every instance and never mutated in place (a company name, a fixed tax rate). Any per-object collection — a list, a dictionary — belongs in __init__ as an instance attribute instead.

try_it.py
Click "Run Code" — try removing self.items = [] from __init__ to see the bug come back.
Go Deeper: checking with is to confirm it's really the same object

cart1.items is cart2.items returns True in the buggy version above and False in the fixed one — is (from Chapter 8) checks whether two names point at the literal same object in memory, which is the most direct way to confirm this bug's actual cause.

Quick recap
  • A class attribute is defined in the class body and shared by every instance.
  • An instance attribute, set in __init__ with self.name = value, belongs to one object only.
  • A mutable class attribute (like a list) is silently shared and mutated across every instance — give each object its own copy in __init__ instead.
Sub-topic 5 of 6

5. Common dunder ("magic") methods

At a glance
  • A dunder method is a method with double underscores on both sides, like __init__, that Python calls automatically in specific situations.
  • __str__ controls what print(obj) and str(obj) show.
  • __repr__ is a closely related dunder meant for an unambiguous, developer-facing description.
Why this matters: Sub-topic 1's default printout, <__main__.BankAccount object at 0x7f2a...>, tells a user precisely nothing useful — a memory address is meaningless to anyone reading program output.

__init__ was this chapter's first dunder method — "dunder" is short for double underscore, referring to the __ on each side of the name. Python defines several dunders that get called automatically in specific situations, rather than being called directly by name.

What is... a dunder method? A dunder ("magic") method is a method named with double underscores before and after, like __init__ or __str__, that Python calls automatically for a specific built-in operation — object creation, printing, comparisons, and more — instead of being called directly.

Without a __str__, printing an object falls back to that unhelpful default:

no_str_demo.py
class BankAccount:
    def __init__(self, owner, balance):
        self.owner = owner
        self.balance = balance

acct = BankAccount("Alice", 100)
print(acct)
actual output of no_str_demo.py — a memory address, meaningless to any reader
<__main__.BankAccount object at 0x7c347b890d70>

Defining __str__ tells Python exactly what print(acct) should show instead:

str_demo.py
class BankAccount:
    def __init__(self, owner, balance):
        self.owner = owner
        self.balance = balance

    def __str__(self):
        return f"BankAccount(owner={self.owner!r}, balance={self.balance})"

acct = BankAccount("Alice", 100)
print(acct)
actual output of str_demo.py
BankAccount(owner='Alice', balance=100)
What is... __str__? __str__ is a method that must return a string, called automatically whenever an object is passed to print() or str(). It's how a class controls its own readable, human-facing description.

__repr__ is a close sibling, meant for an unambiguous description aimed at a developer inspecting a value (in a debugger, or typed directly at an interactive prompt), rather than end-user-facing output. If __str__ is missing, print() falls back to __repr__ instead of the raw memory address:

repr_demo.py
class BankAccount:
    def __init__(self, owner, balance):
        self.owner = owner
        self.balance = balance

    def __str__(self):
        return f"BankAccount(owner={self.owner!r}, balance={self.balance})"

    def __repr__(self):
        return f"BankAccount({self.owner!r}, {self.balance})"

acct = BankAccount("Alice", 100)
print(acct)
print(str(acct))
print(repr(acct))
actual output of repr_demo.py
BankAccount(owner='Alice', balance=100)
BankAccount(owner='Alice', balance=100)
BankAccount('Alice', 100)
What is... __repr__? __repr__ returns a developer-facing description of an object, used by repr() and shown automatically when an object is typed directly at an interactive prompt. A common convention is writing it to look like the exact code that would recreate the object, as BankAccount('Alice', 100) does above.

A class only strictly needs __str__ for this chapter's purposes — __repr__ is worth recognizing by name, but not something every class here is required to define.

try_it.py
Click "Run Code" — try removing __str__ to see the default printout return.
Go Deeper: there are many more dunders than __str__ and __repr__

__eq__ (controls ==), __len__ (controls len(obj)), and __add__ (controls +) are a few of many others — each one hooks a class into a built-in Python operation. __str__ is simply the one nearly every custom class ends up needing.

Quick recap
  • A dunder method has double underscores on both sides and is called automatically by Python, not by name directly.
  • __str__ controls what print(obj) and str(obj) display.
  • __repr__ is the developer-facing counterpart, used as a fallback by print() and shown at an interactive prompt.
Sub-topic 6 of 6

6. Real-world OOP basics in production

At a glance
  • A realistic inventory system bundles data and behavior for each product into one class, instead of parallel lists or a pile of loose dictionaries.
  • Every sub-topic in this chapter shows up together: __init__ for setup, instance methods for behavior, a class attribute for shared configuration, and __str__ for readable output.
  • Inheritance, polymorphism, and @staticmethod/@classmethod/@property are real, useful tools — and exactly what Chapters 15 and 16 build on top of this foundation.
Pattern to remember: reach for a class the moment several pieces of data always travel together and have behavior specific to them — that combination is the actual signal, not "everything should be a class."

Picture a small store's inventory tracked the way earlier chapters would have handled it — a list of dictionaries, plus separate functions that each have to know the dictionary's exact shape:

before_classes.py
def restock(product, amount):
    product["quantity"] += amount

def sell(product, amount):
    if amount > product["quantity"]:
        print("Not enough stock.")
        return
    product["quantity"] -= amount

widget = {"name": "Widget", "quantity": 10, "price": 4.99}
restock(widget, 5)
sell(widget, 3)
print(widget)
actual output of before_classes.py
{'name': 'Widget', 'quantity': 12, 'price': 4.99}

This works for one small script, but nothing connects restock and sell to the dictionary shape they depend on — a typo like product["qty"] would fail silently in a different part of a larger program. A Product class bundles the data and its behavior into one guaranteed shape instead:

product_class.py
class Product:
    store_name = "Downtown Hardware"  # shared by every Product

    def __init__(self, name, quantity, price):
        self.name = name
        self.quantity = quantity
        self.price = price

    def restock(self, amount):
        self.quantity += amount

    def sell(self, amount):
        if amount > self.quantity:
            print("Not enough stock.")
            return
        self.quantity -= amount

    def __str__(self):
        return f"{self.name}: {self.quantity} units @ ${self.price:.2f}"

widget = Product("Widget", 10, 4.99)
widget.restock(5)
widget.sell(3)
print(widget.store_name, "-", widget)
actual output of product_class.py
Downtown Hardware - Widget: 12 units @ $4.99

Every sub-topic from this chapter is doing real work in that one class: __init__ guarantees every Product has the same three attributes, restock and sell are instance methods that only ever touch their own object's data, store_name is a class attribute because it's genuinely the same for every product in this one store, and __str__ makes print(widget) actually useful instead of a memory address.

This is also exactly where a program built entirely from loose dicts and functions starts to strain: adding a tenth kind of product-related function means checking every one of them still assumes the same dictionary shape everywhere it's called. A class keeps that shape and its behavior defined in exactly one place.

What this chapter deliberately leaves out is just as important as what it covers. Every Product above is a completely separate, unrelated class — there's no way yet to say "a PerishableProduct is a Product, plus an expiration date." That relationship, called inheritance, along with polymorphism and the @staticmethod/@classmethod/@property decorators, is exactly what Chapters 15 and 16 build directly on top of everything learned here.

Go Deeper: how do you know when something deserves to be a class?

A good signal: does this data always travel together, and does it have behavior that only makes sense applied to that specific data? A Product's name, quantity, and price always travel together, and restock/sell only make sense applied to one specific product — that combination is the actual signal, not simply "this program has gotten big."

Quick recap
  • A class bundles data and behavior together, replacing parallel dictionaries and loose functions that all have to agree on a shape by convention alone.
  • This chapter's Product example uses every sub-topic together: __init__, instance methods, a class attribute, and __str__.
  • Inheritance, polymorphism, and @staticmethod/@classmethod/@property build directly on this foundation in Chapters 15 and 16.
In the Real World

Points to Remember

← All Chapters Take the Quiz →