9.1. OOP Design and Methods#
Required core: this notebook develops class definitions, instances, method binding, initialization, properties, and representations. Run demonstration cells in order. The banking contract is introduced below.
9.1.1. Why Object-Oriented Programming?#
Procedural programs often pass the same data through many separate functions. For example, the deposit() and withdraw() functions of a banking account management program share the parameters owner, balance, and amount.
def deposit(owner, balance, amount):
return owner, balance + amount
def withdraw(owner, balance, amount):
if amount > balance:
raise ValueError("Insufficient funds")
return owner, balance - amount
...
...
You could save these functions in a file called banking.py, then run import banking in the Python shell to use them.
>>> import banking
>>> banking.deposit('Tom', 1000, 100)
('Tom', 1100)
>>>
This procedural style can work well for small scripts, but once the banking program starts to grow in the number of functions (which will eventually become non-trivial), it becomes harder to keep track of which data (the parameters) belongs together and which functions are allowed to change it.
The same problem will occur when you model programs and systems based on real world things like library management information, student information system, or even game characters.
Object-Oriented Programming (OOP) helps by organizing related data and behavior (functions/methods) into a class, which you then use to create objects.
Key Benefits of Using OOP include:
Modularity and Organization: OOP allows you to structure your code by breaking complex systems into smaller, manageable pieces (classes). This makes the code easier to navigate and maintain as projects grow.
Code Reusability: Through inheritance, you can create a base class and reuse its logic in multiple child classes, adhering to the “Don’t Repeat Yourself” (DRY) principle.
Easier Debugging: Because data and the functions that manipulate it are bundled together in objects, it is often easier to isolate and fix errors without affecting the rest of the program.
Real-World Modeling: OOP makes it intuitive to model real-world entities like “Users,” “BankAccount” objects, or “GameCharacters” by giving them specific properties (attributes) and actions (methods).
Python is object-oriented at its core. While Python is multi-paradigm and allows for functional or procedural styles, OOP is its core foundation. In fact, everything in Python is an object, including integers and strings. You can see this in the values you already use: each one has methods, functions defined inside its class.
Value |
Type (Class) |
Example method |
|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
When you call [1, 2, 3].sort(), you are calling a method on a list object. This chapter applies the same idea to classes you define.
Note the column header Type (Class): in Python 3, the two words mean the same thing. Every class you define is a type, and every built-in type like str or list is a class. The terms are used interchangeably throughout this chapter.
Before writing a class, identify the state it owns and the operations callers need. For BankAccount, the owner and balance belong together. Its operations should preserve an invariant, a condition that remains true after construction and every successful public operation.
Design decision |
Account contract |
|---|---|
State |
Owner and balance |
Initial state |
Balance is nonnegative |
Public updates |
Deposit a positive amount; withdraw a positive amount within the balance |
Failure |
Reject invalid amounts before changing the balance |
Observation |
Read |
Functions can validate too, but with the procedural version the caller holds owner and balance as loose variables: any line of code can set balance = -500 between calls, or pass one account’s balance with another’s owner. A class keeps the state inside one object and routes every change through its methods, so the invariant is checked wherever the balance changes. A small procedural script remains a reasonable choice when only a few lines touch the data and there is a single copy of it.
9.1.2. Classes and Instances#
A class is a blueprint that defines data and behavior. An instance is one concrete object created from that blueprint.
Think of a class as a cookie cutter and each instance as an individual cookie. The cutter defines the shape; every cookie produced from it is a separate object with its own toppings (attributes).
Term |
Meaning |
Cookie analogy |
|---|---|---|
Class |
Blueprint / template |
The cookie cutter |
Instance |
One object made from the class |
A specific cookie |
Attribute |
Data stored on the instance |
Icing color, sprinkles |
Method |
Function that belongs to the class |
|
The basic syntax for defining a class in Python looks like this:
class ClassName:
"""Optional docstring describing the class."""
def __init__(self, attribute1, attribute2): # initializer
self.attribute1 = attribute1 # store data on the instance
self.attribute2 = attribute2
def method_name(self, other_param): # instance method
# self always refers to the current instance
return self.attribute1 + other_param
class ClassName:declares a new class (use PascalCase by convention)__init__: the initializer Python calls on the new instance. Calling the class creates the object;__init__sets its initial state and must returnNoneself: the instance itself; Python passes it automaticallydef method_name(self, ...): any method that operates on the instance
Here is a simple Point class. As you can see, it creates 2D points and can calculate the distance between two points.
class Point:
"""Represent a 2D point with x and y coordinates."""
def __init__(self, x, y):
self.x = x
self.y = y
def distance_to(self, other):
"""Return Euclidean distance from this point to another Point."""
return ((self.x - other.x) ** 2 + (self.y - other.y) ** 2) ** 0.5
### Point has no __str__ method yet, so printing a Point shows Python's default
### representation, which is not very informative. The __str__ Method subsection
### later in this section explains the commented-out method below.
# def __str__(self):
# return f"Point({self.x}, {self.y})"
You create instances by calling the class like a function:
p = Point(3, 4) # one point object
q = Point(0, 0) # another point object
print(p)
print(q)
print(p.distance_to(q))
<__main__.Point object at 0x7ff0f08bcec0>
<__main__.Point object at 0x7ff0c9e856d0>
5.0
Even though the points come from the same class, they are independent objects.
r = Point(3, 4) # a third point object with the same coordinates as p
s = Point(3, 4) # a fourth point object with the same coordinates as p and r
print(r is s)
print(r == s)
False
False
Both results are false here: r and s are separate instances, and this class has not defined value equality. Equal coordinates do not yet make two points compare equal. Advanced OOP Topics develops __eq__; is will continue to test identity.
9.1.2.1. Custom and Built-in Types#
Two built-in tools let you inspect objects:
type(obj): returns the class of the objectisinstance(obj, SomeClass): returnsTrueifobjis an instance of that class (or a subclass)
Compare a Point instance with built-in values.
Takeaway: user-defined class instances behave like built-in objects under type() and isinstance().
p = Point(3, 4)
print(type(p)) ### <class '__main__.Point'>
print(type(p) is Point) ### True
print(isinstance(p, Point)) ### True
print(isinstance(p, str)) ### False
### Custom types/classes and built-in types work the same way
print(type("hello")) ### <class 'str'>
print(type("hello") is str) ### True
print(isinstance(42, int)) ### True
print(isinstance(42, float)) ### False
<class '__main__.Point'>
True
True
False
<class 'str'>
True
True
False
### Exercise: Classes vs Instances
# 1. Define a class `Book` with `title` and `author` in `__init__`.
# 2. Create two instances with different titles.
# 3. Print each instance's title and author on separate lines.
# 4. Print `book1 is book2` to verify they are different objects.
# 5. Print `isinstance(book1, Book)`.
### Your code starts here.
### Your code ends here.
Python Design - A. Chen
Data Workflows - B. Diaz
False
True
9.1.3. A Calculator Class#
The Point class above is your first class: it stores two values and has one method. Here is a second sample class, CalcTwo, a calculator that performs operations on two input numbers. Its methods also use self because they belong to an instance, and the class shows that one class can contain several methods.
class CalcTwo:
"""Represents a calculator for operations on two numbers."""
def __init__(self):
self.last_result = None # Keep track of the most recent calculation
def add(self, a, b):
"""Return a + b."""
self.last_result = a + b # Save result on this instance
return self.last_result
def subtract(self, a, b):
"""Return a - b."""
self.last_result = a - b
return self.last_result
def multiply(self, a, b):
"""Return a * b."""
self.last_result = a * b
return self.last_result
def divide(self, a, b):
"""Return a / b."""
if b == 0:
raise ValueError("Cannot divide by zero") # Avoid undefined operation
self.last_result = a / b
return self.last_result
def __str__(self):
return f"CalcTwo(last_result={self.last_result})"
Key parts of the code above:
Part |
What it does |
|---|---|
|
Declares the class |
|
Initializer; runs on the new instance when you call |
|
Controls what |
|
The instance being created or used; Python passes it automatically |
|
Stores the most recent result on this instance |
|
Returns the sum of two numbers |
|
Returns the difference of two numbers |
|
Returns the product of two numbers |
|
Returns the quotient of two numbers |
__init__(): The initializer, called automatically on a newCalcTwoinstance.__str__(): Returns a readable string representation of the calculator state.Arithmetic methods: each method takes two numbers and returns a computed result.
last_result: lets each instance remember its own most recent calculation.
Now create two instances of CalcTwo: c1 and c2. After creating them, you can:
access data in the object (e.g.,
c1.last_result)make method calls with two numbers (e.g.,
c1.add(5, 2),c1.subtract(9, 4))
c1 = CalcTwo()
c2 = CalcTwo()
print(c1.add(10, 5)) # 15
print(c1.subtract(10, 3)) # 7
print(c1.multiply(4, 6)) # 24
print(c2.divide(21, 3)) # 7.0
print(c1.last_result) # 24 (independent from c2)
print(c2.last_result) # 7.0
print(c1)
15
7
24
7.0
24
7.0
CalcTwo(last_result=24)
Each method receives a particular object as self. Trace the calls above by recording both instances’ state; a call on one calculator does not update the other.
After call |
Returned value |
|
|
|---|---|---|---|
|
15 |
15 |
|
|
7 |
7 |
|
|
24 |
24 |
|
|
7.0 |
24 |
7.0 |
The return value and the stored attribute happen to agree here, but they are different parts of the method’s interface. A method can return a value, change state, do both, or do neither.
9.1.3.1. Defining Methods#
CalcTwo.add is a method: a function defined inside a class. To see what that adds, compare it with a standalone function that does the same job. The function receives the calculator as an ordinary parameter, calc.
def add_two(calc, a, b):
calc.last_result = a + b
return calc.last_result
The method version, which CalcTwo already defines, moves the same logic inside the class and renames the first parameter from calc to self. The name self is a convention, not a syntax rule.
class CalcTwo:
def add(self, a, b):
self.last_result = a + b
return self.last_result
To call either version, first create a CalcTwo object.
calc = CalcTwo()
add_two(calc, 9, 4)
13
The standalone function takes the calculator as an explicit argument. The method can be called the same way, through the class; this function-style syntax is less common.
CalcTwo.add(calc, 9, 4)
13
In this version, CalcTwo is the class name, add is the method name, and calc is passed explicitly as the first argument.
The second (and more idiomatic) way is method syntax:
calc.add(9, 4)
13
Both calls return the same result.
The receiver object is assigned to the first parameter, so inside the method, self refers to the same object as calc.
print(calc.last_result)
13
In method syntax, calc is the object the method is invoked on (the receiver).
Regardless of syntax, behavior is the same:
CalcTwo.add(calc, 9, 4) and calc.add(9, 4) both use the same method implementation.
A method is also a value. Without parentheses, calc.add refers to a bound method: the method together with the object it belongs to. You can store it in a variable and call it later. With parentheses, calc.add(2, 3) calls it immediately.
action = calc.add # no parentheses: store the bound method
result = action(2, 3) # call it later, just like calc.add(2, 3)
print(result) # 5
print(calc.last_result) # 5, because action is bound to calc
5
5
Class methods, introduced in Advanced OOP Topics, can be stored and called later in the same way.
### Exercise: Defining Methods
# This standalone function computes a rectangle's area:
# def rect_area(rect):
# return rect.width * rect.height
# 1. Define a class Rectangle whose __init__(self, width, height) stores both values.
# 2. Rewrite rect_area as a method area(self) inside the class.
# 3. Create r = Rectangle(3, 5) and call the method both ways:
# Rectangle.area(r) and r.area().
# 4. Store the bound method r.area in a variable, then call the variable.
### Your code starts here.
### Your code ends here.
15
15
15
9.1.4. A BankAccount Class#
This banking version uses the contract introduced above: a nonnegative starting balance, positive deposits and withdrawals, a read-only public balance, and validation before mutation. Both update methods return self, so callers may keep the account result or ignore it. Returning self does not create a second account.
The class combines three special methods, also called dunder methods because their names begin and end with double underscores, with one property:
Feature |
Used by |
Purpose |
|---|---|---|
|
|
Initialize the new object’s state |
|
|
Human-readable text |
|
|
Diagnostic, ideally reconstructable text |
|
|
Read through attribute syntax without a public setter |
A property is not a dunder method. The complete definition below lets you see how these features fit together; the following subsections explain each feature.
class BankAccount:
"""A teaching account with controlled balance updates."""
def __init__(self, owner="Unknown", balance=0.0):
if balance < 0:
raise ValueError('Starting balance cannot be negative')
self.owner = owner
self._balance = balance
@property
def balance(self):
"""Current balance, read-only through the public interface."""
return self._balance
def deposit(self, amount):
if amount <= 0:
raise ValueError('Deposit must be positive')
self._balance += amount
return self
def withdraw(self, amount):
if amount <= 0:
raise ValueError('Withdrawal must be positive')
if amount > self._balance:
raise ValueError('Insufficient funds')
self._balance -= amount
return self
def __str__(self):
return f"BankAccount(owner={self.owner}, balance=${self._balance:.2f})"
def __repr__(self):
return f"BankAccount({self.owner!r}, {self._balance!r})"
acct1 = BankAccount("Ava", 945.30)
acct2 = BankAccount("Max", 500.00)
Predict the balance after each operation, then run the cell. Successful updates return the same account object. A rejected withdrawal raises an exception before any subtraction, preserving the balance.
account = BankAccount('Ava', 100)
returned = account.deposit(50)
print(account.balance, returned is account) # 150 True
try:
account.withdraw(200)
except ValueError as error:
print(error) # Insufficient funds
print(account.balance) # 150, unchanged
try:
account.deposit(-20)
except ValueError as error:
print(error) # Deposit must be positive
print(account.balance) # 150, unchanged
150 True
Insufficient funds
150
Deposit must be positive
150
Operation |
Balance before |
Balance after |
Result |
|---|---|---|---|
|
100 |
150 |
The same account object |
|
150 |
150 |
|
|
150 |
150 |
|
9.1.4.1. The __init__ Method#
The most special of the special methods is __init__, so-called because it
initializes the attributes of a new object. Here is the __init__ method
from the BankAccount class:
def __init__(self, owner="Unknown", balance=0.0):
if balance < 0:
raise ValueError('Starting balance cannot be negative')
self.owner = owner
self._balance = balance
When you instantiate a BankAccount object, Python invokes __init__ automatically
and passes along the arguments. So you can create an object and set its initial balance
at the same time.
account = BankAccount("Ava", 94.00)
print(account)
BankAccount(owner=Ava, balance=$94.00)
Both parameters are optional. If you call BankAccount with no arguments,
you get the default values ("Unknown" and 0.0).
account = BankAccount()
print(account)
BankAccount(owner=Unknown, balance=$0.00)
If you provide one argument, it overrides owner:
account = BankAccount("Sam")
print(account)
BankAccount(owner=Sam, balance=$0.00)
If you provide two arguments, they override owner and balance.
account = BankAccount("Sam", 45.00)
print(account)
BankAccount(owner=Sam, balance=$45.00)
When you write a new class, start with __init__, which makes objects easy
to create, and __str__, which is useful for debugging.
9.1.4.2. Properties#
The @property decorator lets you define a method that behaves like an attribute.
This is useful when you want controlled read-only (or validated) access to a
value stored on the object, without changing how callers access it.
Here is the balance property from the BankAccount class:
@property
def balance(self):
"""Current balance, read-only through the public interface."""
return self._balance
The underscore in _balance signals that it is an internal attribute: callers
should use the balance property rather than accessing _balance directly.
acct = BankAccount("Mia", 150.0)
# Access like an attribute, with no parentheses
print(acct.balance) # 150.0
# Attempting to set it raises AttributeError (read-only)
try:
acct.balance = 9999
except AttributeError as e:
print(f"Error: {e}")
# Use deposit and withdraw to change the balance
acct.deposit(50.0)
acct.withdraw(30.0)
print(acct.balance) # 170.0
150.0
Error: property 'balance' of 'BankAccount' object has no setter
170.0
The property blocks normal assignment such as acct.balance = 9999; it is not a security boundary. A caller can still access _balance, but doing so bypasses the interface and its invariant.
### Exercise: Properties
# Define a class Temperature that stores a reading in degrees Celsius.
# 1. __init__(self, celsius=0.0) raises ValueError if celsius is below -273.15
# (absolute zero); otherwise it stores the value in _celsius.
# 2. Add a read-only property celsius that returns _celsius.
# 3. Add a read-only property fahrenheit that returns celsius * 9 / 5 + 32.
# 4. Create t = Temperature(25) and print both properties.
# 5. Try t.celsius = 30 and print the AttributeError message.
# 6. Try Temperature(-300) and print the ValueError message.
### Your code starts here.
### Your code ends here.
25 77.0
property 'celsius' of 'Temperature' object has no setter
Temperature cannot be below absolute zero
9.1.4.3. The __str__ Method#
When you write a class, you can define a method named __str__ to control
how Python converts instances to a string.
For example, here is the __str__ method from the BankAccount class:
def __str__(self):
return f"BankAccount(owner={self.owner}, balance=${self._balance:.2f})"
This method returns a formatted string. You can invoke it directly:
acct2 = BankAccount("Max", 500.00)
acct2.__str__()
'BankAccount(owner=Max, balance=$500.00)'
But Python can also invoke it for you.
If you use the built-in function str to convert a BankAccount object to a string, Python uses the __str__ method in the class.
str(acct2)
'BankAccount(owner=Max, balance=$500.00)'
And it does the same if you print a BankAccount object.
print(acct2)
BankAccount(owner=Max, balance=$500.00)
Methods like __str__ are called special methods, or dunder methods (short for “double underscore”).
You can identify them because their names begin and end with two underscores.
9.1.4.4. The __repr__ Method#
__repr__ returns a string that ideally looks like a valid Python expression
that could recreate the object. It is used in the interactive interpreter and
by repr(). When __str__ is not defined, Python falls back to __repr__.
Method |
Called by |
Purpose |
|---|---|---|
|
|
Human-readable output |
|
|
Unambiguous, ideally reconstructable |
Here is the __repr__ method from the BankAccount class:
def __repr__(self):
return f"BankAccount({self.owner!r}, {self._balance!r})"
acct = BankAccount("Ava", 945.30)
print(str(acct)) # BankAccount(owner=Ava, balance=$945.30)
print(repr(acct)) # BankAccount('Ava', 945.3)
BankAccount(owner=Ava, balance=$945.30)
BankAccount('Ava', 945.3)
!r requests the representation of each inserted value. This preserves quotes and escapes inside names instead of manually surrounding a name with single quotes. Predict which quoting style appears for the next owner; either style is valid as long as it represents the string correctly.
quoted_owner = BankAccount("O'Neil", 100)
print(repr(quoted_owner)) # BankAccount("O'Neil", 100)
BankAccount("O'Neil", 100)
### Exercise: String Representations
# Extend the Temperature class from the Properties practice.
# 1. Add __str__ returning the reading with one decimal place, like "25.0 C".
# 2. Add __repr__ returning text like "Temperature(25)"; use !r for the value.
# 3. Create t = Temperature(25), then print str(t), repr(t), and t itself.
### Your code starts here.
### Your code ends here.
25.0 C
Temperature(25)
25.0 C
9.1.5. Exercises#
These tasks combine the class features from this section.
### Exercise: Independent Class Practice
# Build a new class without using `BankAccount`.
# 1. Define a class `TaskList` whose `__init__` takes `owner`, stores it,
# and starts `tasks` as a new empty list.
# 2. Add `add_task(task)` to append one task to the list.
# 3. Add `task_count()` to return how many tasks are stored.
# 4. Create t1 and t2 with different owners, add tasks to each.
# 5. Add a read-only count property returning task_count().
# 6. Add __str__ returning "owner: N tasks" and __repr__ using !r on owner and tasks.
# 7. Print each owner with count, compare counts, and print str(t1) and repr(t1).
### Your code starts here.
### Your code ends here.
Lia 2
Noah 1
True
Lia: 2 tasks
TaskList('Lia', ['Draft proposal', 'Email team'])
### Exercise: Section Review
# 1. Define a class `Wallet` with attributes `owner` and `cash`.
# 2. Add a method `spend(amount)` that subtracts from `cash`. It raises
# `ValueError` if amount is not positive or is greater than available
# cash, before changing `cash`.
# 3. Create `w = Wallet("Kai", 40)` and call `w.spend(15)`.
# 4. Print the remaining cash.
# 5. Call `w.spend(-5)` inside try/except and print the error message.
### Your code starts here.
### Your code ends here.
25
Amount must be positive