Skip to content

Module 11 · Object-Oriented Programming — topic 11 of 25

Instance methods

Ordinary methods that work with a specific object through self: reading and changing state, enforcing rules, and the difference from class and static methods.

Beginner 8 min read·Lesson 168 of 306 in Python Programming

Learning objectives

  • Write instance methods that use and change object state
  • Enforce rules inside methods
  • Know when a method should be an instance method

Definition

An instance method is a regular method defined with self as its first parameter. It operates on a particular instance and can read and modify that instance's attributes and call its other methods.

Introduction

Most methods you write are instance methods: deposit, withdraw, add_item, move. They exist to work with one particular object's data.

Why it matters

Instance methods are where an object's rules live. Putting the rule 'balance can't go negative' inside withdraw guarantees it is applied everywhere.

Detailed explanation

An instance method takes self first and is called on an object: obj.method(args).

It can read attributes (self.balance), change them, and call other instance methods (self.log(...)).

If a method doesn't use self at all, it is probably better as a static method or a module-level function; if it only needs the class, make it a class method.

Validation in instance methods protects the object's invariants — the conditions that must always be true.

Methods can return values (queries), change state (commands), or both when it is natural (pop removes and returns an item).

Behind the scenes, obj.method(x) is translated into ClassName.method(obj, x). That is why self appears in the definition but not in the call, and why forgetting self in the definition causes a 'takes 1 positional argument but 2 were given' error.

Syntax

Python
class Account:
def __init__(self, balance=0):
self.balance = balance
def withdraw(self, amount):
if amount > self.balance:
raise ValueError("insufficient funds")
self.balance -= amount
return self.balance
  • First parameter is self.
  • Reads and changes this object.
  • Enforces the object's rules.

Code examples

Reading and changing state

Python
class Light:
def __init__(self):
self.on = False
def toggle(self):
self.on = not self.on
def status(self):
return "ON" if self.on else "OFF"
l = Light()
l.toggle()
print(l.status())
l.toggle()
print(l.status())
Output
ON
OFF

Enforcing a rule

Python
class Account:
def __init__(self, balance=0):
self.balance = balance
def withdraw(self, amount):
if amount > self.balance:
raise ValueError(f"insufficient funds: balance {self.balance}")
self.balance -= amount
return self.balance
a = Account(500)
print(a.withdraw(200))
try:
a.withdraw(1000)
except ValueError as e:
print(e)
Output
300
insufficient funds: balance 300

More examples

Methods working together

Python
class Stopwatch:
def __init__(self):
self.laps = []
self.last = 0
def lap(self, now):
if now < self.last:
raise ValueError("time can't go backwards")
self.laps.append(now - self.last)
self.last = now
return self.laps[-1]
def fastest(self):
return min(self.laps) if self.laps else None
def summary(self):
return f"{len(self.laps)} laps, fastest {self.fastest()}s, total {self.last}s"
sw = Stopwatch()
for t in [62, 121, 185, 243]:
sw.lap(t)
print(sw.laps)
print(sw.summary())
Output
[62, 59, 64, 58]
4 laps, fastest 58s, total 243s

Step-by-step explanation

  • lap converts an absolute time into a lap duration and remembers the new reference time.
  • It refuses times that go backwards, protecting the data.
  • summary calls fastest through self, combining two instance methods.

Expected output

Running “Methods working together” prints exactly:

TextOutput
[62, 59, 64, 58]
4 laps, fastest 58s, total 243s

Practical applications

  • file.write(), list.append(), str.split() are instance methods of built-in types.
  • Game objects' update() and draw() methods run every frame.

Best practices

  • Use instance methods for behaviour that depends on object state.
  • Validate inputs before changing state.
  • Keep methods small and focused.

Common mistakes

An instance method that ignores self

Avoid

def celsius_to_f(self, c):
return c * 9 / 5 + 32

Prefer

@staticmethod
def celsius_to_f(c):
return c * 9 / 5 + 32

If no object data is used, it isn't really an instance method.

Important notes

  • Instance methods can be replaced on a single object, but that's rarely a good idea.

Key takeaways

  • Instance methods take self and work on one object.
  • They read and change state and enforce rules.
  • Methods not using self may belong elsewhere.

Try it yourself

  1. 1
    Add a transfer_to(other, amount) instance method to an Account class.
  2. 2
    Write a Timer class with start, stop and elapsed methods using numbers instead of real time.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

16 questions cover the “Object-Oriented Programming” module. Answers and explanations are revealed after you submit.

  • ModerateWhat is printed?
  • ModerateWhat is printed?
  • ModerateWhat is printed?
Practise this module