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
- A class is a blueprint; an object is a real thing built from it — the same distinction as a cookie cutter and an actual cookie.
- Sub-topics build on each other — what a class even is, then how
__init__sets up each object's own data, then methods that act on that data, then the difference between data shared by every object and data unique to one, then making objects print nicely, then tying it all together. - This chapter allows general class definitions for the first time. Chapter 12 only allowed defining custom exception classes; from here on, any class is fair game — but
@staticmethod,@classmethod,@property, and inheritance (class Child(Parent):) are still off-limits until Chapters 15 and 16.
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.
1. Classes & objects
- 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.
{"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.
A minimal class needs only the class keyword and a name,
written in CapitalizedWords by convention:
class BankAccount:
pass
print(BankAccount)
print(type(BankAccount))
<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:
class BankAccount:
pass
acct = BankAccount()
print(acct)
print(type(acct))
<__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:
print(type("hello"))
print(type(42))
print(type([1, 2, 3]))
print(type({"a": 1}))
<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.
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.
- 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.
2. The __init__ method & instance attributes
__init__is a special method that runs automatically every time a new object is created.selfrefers to the specific object being created or acted on — it's always the first parameter.self.name = valuecreates an instance attribute — data that belongs to that one object only.
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:
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)
Alice 100
Bob 250
__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.
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:
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 -> 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.
__init__runs automatically whenClassName(...)creates a new object.selfis the object itself, filled in automatically as the first parameter of every method.self.name = valuecreates an instance attribute — data unique to that one object.
3. Instance methods
- An instance method is a function defined inside a class that operates on one object's own data via
self. selfis 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 passesacctin asself; nothing extra is written at the call site.
BankAccount can only store data so far. An instance
method adds behavior that reads and changes an object's own
attributes:
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)
150
120
Insufficient funds.
120
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:
acct1 = BankAccount("Alice", 100)
acct2 = BankAccount("Bob", 250)
acct1.deposit(20)
acct2.withdraw(50)
print(acct1.owner, acct1.balance)
print(acct2.owner, acct2.balance)
Alice 120
Bob 200
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.
- An instance method is a function inside a class that takes
selfas its first parameter. selfrefers 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.
4. Class attributes vs. instance attributes
- 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.
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 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)
Acme Corp Alice 60000
Acme Corp Bob 55000
__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:
Employee.company_name = "Acme Corporation"
print(emp1.company_name)
print(emp2.company_name)
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.
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.
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:
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)
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.
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.
- A class attribute is defined in the class body and shared by every instance.
- An instance attribute, set in
__init__withself.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.
5. Common dunder ("magic") methods
- A dunder method is a method with double underscores on both sides, like
__init__, that Python calls automatically in specific situations. __str__controls whatprint(obj)andstr(obj)show.__repr__is a closely related dunder meant for an unambiguous, developer-facing description.
<__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.
__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:
class BankAccount:
def __init__(self, owner, balance):
self.owner = owner
self.balance = balance
acct = BankAccount("Alice", 100)
print(acct)
<__main__.BankAccount object at 0x7c347b890d70>
Defining __str__ tells Python exactly what
print(acct) should show instead:
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)
BankAccount(owner='Alice', balance=100)
__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:
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))
BankAccount(owner='Alice', balance=100)
BankAccount(owner='Alice', balance=100)
BankAccount('Alice', 100)
__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.
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.
- A dunder method has double underscores on both sides and is called automatically by Python, not by name directly.
__str__controls whatprint(obj)andstr(obj)display.__repr__is the developer-facing counterpart, used as a fallback byprint()and shown at an interactive prompt.
6. Real-world OOP basics in production
- 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/@propertyare real, useful tools — and exactly what Chapters 15 and 16 build on top of this foundation.
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:
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)
{'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:
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)
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.
- Real inventory, user-account, and order-tracking systems all bundle related data and behavior into classes exactly like
Productabove, rather than passing loose dictionaries between unrelated functions. - Class attributes model genuinely shared configuration (a store name, a tax rate) while instance attributes model what's unique to each object — mixing the two up is a real, common source of bugs in production code.
__str__is why printing a real-world object in a Python program (a database row, an API response) usually shows something readable instead of a raw memory address.
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."
- 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
Productexample uses every sub-topic together:__init__, instance methods, a class attribute, and__str__. - Inheritance, polymorphism, and
@staticmethod/@classmethod/@propertybuild directly on this foundation in Chapters 15 and 16.
- Nearly every real Python codebase — web frameworks, data pipelines, game engines — is organized around classes bundling related data and behavior, exactly like this chapter's
BankAccountandProduct. - The mutable class-attribute bug from Sub-topic 4 is a genuinely common real-world mistake, not a toy example — it shows up whenever a class accidentally defines a list or dictionary at the class level instead of inside
__init__. - A missing
__str__is why debugging real production code sometimes shows a wall of<object at 0x...>noise in logs — defining it is a small habit that pays off constantly when reading real output.
Points to Remember
- A class is a blueprint; an object (instance) is one real thing built from it with
ClassName()— every value in Python, including strings and lists, is already an object of some class. __init__runs automatically when an object is created, andself.name = valueinside it sets up that object's own instance attributes;selfis always the first parameter of every method, filled in automatically.- An instance method takes
selfand operates on one object's own attributes; callingobj.method(args)passesobjin asselfautomatically. - A class attribute, defined in the class body, is shared by every instance; a mutable class attribute like a list is a real bug risk, since every instance secretly shares and mutates the same object — give each instance its own copy in
__init__instead. __str__controls whatprint(obj)shows;__repr__is the developer-facing counterpart, used as a fallback and at an interactive prompt.- General class definitions are allowed from this chapter forward — but inheritance and
@staticmethod/@classmethod/@propertywait until Chapters 15 and 16.