Classes & instance methods

Model a small piece of state

Lesson 16 of 20 · 14 min · Module 5: A more expressive Python toolkit

A class can keep state and the operations on that state together. Each instance should own its own progress.

Start this lesson →

Free. No installation: you write and run the code in your browser, and it is checked automatically.

By the end, you’ll be able to…

  • Initialize per-instance attributes
  • Keep a class invariant true after updates

The idea

__init__ initializes a new instance. Methods receive that instance as self. Store per-session values on self, rather than as a shared mutable class attribute.

class Counter:
    def __init__(self):
        self.value = 0

    def increment(self):
        self.value += 1

01Name the invariant

The completed count must stay between zero and total. The brief guarantees nonnegative additions, and min enforces the upper boundary.

02Understand self

session.complete(2) passes session into the method as self. Another StudySession instance supplies a different self and therefore different state.

03Test behavior across several calls

One call may work while a sequence of updates breaks the boundary. Test accumulation, saturation, and independence between instances.

Your turn

Create StudySession(total). Store total and completed=0 on each instance. Method complete(amount) adds a nonnegative integer amount but never lets completed exceed total. Method remaining() returns total - completed. total is a nonnegative integer.

What the checks look for

  • Initializes progress for a new session
  • Accumulates progress and caps it at the total
  • Separate sessions keep independent state
  • Handles a zero-sized session
Try it in the editor →

Take this with you

A small class is useful when its data and behavior have one clear responsibility.

Go a little further

Add a reset method and test that resetting one session leaves another unchanged.

Learn Python Foundations for free

20 short lessons with real code and instant checks.

See the whole course →