Lesson · Object-Oriented Python
Classes & Objects
58 min readClasses & Objects
A class defines behavior and usually the rules for constructing instances. Python classes are themselves runtime objects, so object-oriented programming fits naturally into the wider data model.
Learning goals
- Explain the difference between a class object and an instance, and what
BankAccount("Ada", 100)actually does at runtime. - Describe how
__init__bindsownerandbalanceonto the new instance, and whyselfis an ordinary parameter. - Read an attribute access such as
account.balanceas an instance dictionary lookup that falls back to the class. - Predict which state changes when
depositruns, and whether two accounts built from one class share any of it. - Show why adding an attribute to one instance leaves other instances of the same class untouched.
Mental model
Each line is a different runtime object: the class is a callable that stores shared behavior, the instance holds per-account data in its own dictionary, and attribute lookup checks the instance dictionary first. Follow the ownership of a name and you can predict whether two accounts share state or keep independent copies.
Mental model
read it top to bottom
class BankAccount: statement (the class object, holding __init__ and deposit)
↓ calling the class: BankAccount("Ada", 100)
instance with its own dictionary (self.owner, self.balance live here)
↓ account.deposit(50)
method found on the class, bound to that instanceCore idea
A class statement is executable code: it builds a class object whose namespace carries the methods, and each call to that object runs __init__ and hands back a fresh instance. Instance attributes are stored in the instance's own dictionary, while methods are looked up on the class and bound to the instance at call time. The organizing split is behavior on the class, data on the instance.
class
A class statement builds a class object: the body runs once to fill a namespace with methods and class attributes, and the class name ends up bound to that object. Calling the class creates an instance, runs __init__ with the instance as self, and returns it. Passing arguments that __init__ cannot accept raises TypeError before anything is returned.
Instances
An instance is an object created from a class. Attribute lookup starts from the instance and then consults class machinery according to the data model.
Attributes
Attributes associate names with objects through instance or class namespaces and descriptor rules. Attribute access is syntax over a programmable lookup protocol.
Methods
A method is typically a function retrieved through a class and bound by the descriptor protocol. Access through an instance can automatically supply that instance as the first argument.
self
self is the conventional name for the instance parameter of an instance method. It is not a keyword; its meaning comes from normal parameter binding after method binding.
Instance state
Instance state is the information that persists between operations in Classes & Objects. Make ownership explicit so you can predict whether two operations observe the same state or independent copies.
Dynamic attributes
Most normal Python instances can gain attributes at runtime through their instance dictionary. __slots__, custom attribute hooks, and some extension types can change this behavior.
Class objects
Executing a class statement creates a class object. That object is callable, stores class attributes, participates in inheritance, and is itself an instance of a metaclass.
Walkthrough
class BankAccount:runs one statement that puts__init__anddepositinto a new class object; the method bodies do not execute yet.BankAccount("Ada", 100)creates the instance first, then calls__init__withselfbound to it;self.owner = ownerandself.balance = balancewrite into that instance's dictionary. Thebalance=0default applies only when the second argument is omitted.account.deposit(50)looksdepositup on the class, binds it toaccount, checksamount <= 0before mutating, and rebindsself.balanceto the new total with+=.- Predict before running: the value printed by
print(account.balance), whetherBankAccount("Grace")shares state withaccount, and which exceptionaccount.deposit(-5)raises and leaves behind.
Experiments to try
- Create a second account with
BankAccount("Grace", 250), deposit into each, and print both balances to confirm the state is per instance rather than shared. - Call
account.deposit(-5)and read theValueError; move the guard belowself.balance += amountand check whether a failed call can now leave the account in a wrong state. - Set
account.nickname = "trip fund"at runtime, then readBankAccount("Grace").nicknameand explain theAttributeErrorwith the instance dictionary. - Print
BankAccount.depositandaccount.depositside by side and note that one is a plain function while the other is a bound method that already holdsaccount.
Common mistakes
- Forgetting
selfand writingbalance = balanceinside__init__: the line rebinds a local parameter and the instance never gains the attribute, so later reads raiseAttributeError. - Using a mutable default such as
def add_item(self, item, items=[]): the default is evaluated once when the class statement runs, so every instance that omits the argument shares one list. - Calling
BankAccount.deposit(50)instead ofaccount.deposit(50): the unbound function binds50toselfand raisesTypeErrorbefore the body runs. - Assuming an assignment like
account.balance = 0touches the class: it writes only that instance's dictionary, and sibling instances keep their own values.
Practice: Easy
- Run the worked example, then create
BankAccount("Grace", 250). Before running, predict the balance of each account after a single deposit; verify withprintand explain any surprise. - Call
account.deposit(-5)and thenaccount.deposit(0). Record the exact exception text for each and confirmaccount.balanceis unchanged after both calls. - Add
account.nickname = "trip fund", then printhasattr(account, "nickname")next tohasattr(BankAccount("Grace"), "nickname"). Explain each result using the instance dictionary.
Practice: Medium
- Add a
withdraw(self, amount)method that mirrorsdeposit: raiseValueErrorfor a non-positive amount or one aboveself.balance, and return the new balance. Test the boundary whereamount == self.balance. - Print
type(account.deposit)andtype(BankAccount.deposit). State which one bindsselfautomatically, then call the unbound form manually asBankAccount.deposit(account, 50)and confirm the balances match. - Give the class an
interest_rate = 0.02attribute, read it through an instance, then setaccount.interest_rate = 0.05and compareaccount.interest_ratewithBankAccount.interest_rate. Explain which assignment created per-instance data.
Practice: Hard
- Design a
Playlistclass with__init__taking a title,add(song)appending to per-instance state, and__len__returning the count. Write three assertions that pin down which state is shared and which is per instance before implementing. - Build a failure lab around three traps: a missing
selfbinding, a shared mutable default, and an unbound method call. For each, show the smallest class or call that triggers it and name the object-model rule behind the result. - Connect this lesson to the method kinds lesson: decide which parts of
deposit(validation, mutation, returning a value) could move to a@classmethodor@staticmethodand which must stay on the instance, then implement one split and argue for it.
Lesson checklist
- I can explain what the statement
class BankAccount:executes before any account exists. - I can trace how
__init__bindsownerandbalanceonto the new instance. - I can predict whether a name is stored on the instance or on the class before reading it.
- I can name the mechanism behind the
AttributeErrorcaused by a missingself.ownerassignment.
Remember
A class is a runtime object built by an executable statement; calling it produces an instance whose attributes live in its own dictionary, while methods stay on the class and receive that instance as `self`. Keep the split in view: behavior is shared, state is per instance, and every attribute question is really a question about which dictionary was supposed to hold the name.
Interview angles
What is the main purpose of **class**?+
A class statement builds a class object: the body runs once to fill a namespace with methods and class attributes, and the class name ends up bound to that object. Calling the class creates an instance, runs __init__ with the instance as self, and returns it. Passing arguments that __init__ cannot accept raises TypeError before anything is returned.
What should you pay attention to when using **Instances**?+
An instance is an object created from a class. Attribute lookup starts from the instance and then consults class machinery according to the data model.
How does **Attributes** fit into this lesson?+
Attributes associate names with objects through instance or class namespaces and descriptor rules. Attribute access is syntax over a programmable lookup protocol.
Why does `def __init__(self, tags=[])` share one list across instances, and what is the fix?+
Default argument values are evaluated once, when the def executes during the class statement, so every call that omits tags reuses the same list object. Use None as the default and build a fresh list inside __init__ when no value was passed.