Writing
Think Object-Oriented: Classes Explained With an Alarm Clock
Objects hold state and behaviour, and a class is the blueprint you build them from. A refreshed beginner’s guide using an alarm clock in idiomatic Python, with encapsulation, composition and when a function is enough.
By Ka Lun Chan · Learning / Engineering judgment
What does it mean to think object-oriented?
It means modelling a program as objects that each hold their own state (data) and behaviour (methods), the way real things do. An alarm clock knows what time its alarm is set for and whether it’s on, off or snoozing, and it can ring, snooze and stop. A class is the blueprint for that kind of object, and each object you create from it is an instance.
I first wrote this on my old blog. This version keeps the alarm clock and the advice that held up, and fixes the example code, which didn’t actually do what it described.
Object-oriented programming, or OOP, organises code around those objects rather than around a list of steps. Python, Java, C#, Ruby and many other languages support it. The vocabulary is the hard part for beginners, so here it is mapped onto the example used throughout this post:
| OOP term | Alarm clock example | Plain meaning |
|---|---|---|
| Class | AlarmClock | The blueprint. It describes what every alarm clock has and can do. |
| Instance (object) | clock = AlarmClock(time(6, 30)) | One real alarm clock built from the blueprint. |
| State (attributes) | alarm_time, state, snooze_count | What this clock remembers right now. |
| Behaviour (methods) | turn_on(), snooze(), stop() | What the clock can do. Methods usually read or change the state. |
| Encapsulation | _next_ring | Details the outside world shouldn’t touch, kept behind the methods. |
| Inheritance | TravelAlarmClock(AlarmClock) | A more specific kind of the same thing. It is an alarm clock. |
| Composition | AlarmClock(..., sounder=Radio()) | An object built from other objects. It has a radio. |
What is the difference between a class and an object?
A class describes a kind of thing. An object is one specific thing made from that description. Human is a class and you are an instance of it, with your own name, height and mood that nobody else shares.
Would you build a house without a blueprint? The blueprint says every house has rooms, doors and a roof. The houses built from it each have their own paint colour and their own people inside. Python’s classes tutorial describes classes as a way of bundling data and functionality together, and calling the class is how you get a new instance.
The habit I suggested back then still works: look at everything around you and think about it in these terms. Ask what a thing needs to remember, what it can do, and which actions change its state. Practising on real objects makes the vocabulary stick before you meet it in a large codebase.
How would you model an alarm clock as a class?
Give it the state a real alarm clock keeps (the alarm time, whether it’s off, on, ringing or snoozed, and how many times you’ve snoozed) and methods that change that state. The methods should do more than print a message about what happened.
What’s the first thing many of us do every morning? Hit the snooze button a couple of times. That makes the alarm clock a good first object. My original example had the right method names in spirit, but each method only printed a sentence. Calling snooze() didn’t change anything, so the clock had behaviour without state, which is half an object. It also used camelCase names like setAlarmTime. PEP 8 asks for CapWords class names and lowercase method names with underscores, so set_alarm_time is the Python spelling.
Here’s the refreshed version. The states are an Enum, which gives you a fixed set of named values instead of loose strings that are easy to mistype. I added a ringing state because the clock needs somewhere to be while it’s screaming at you.
from datetime import date, datetime, time, timedelta
from enum import Enum, auto
class AlarmState(Enum):
OFF = auto()
ON = auto()
RINGING = auto()
SNOOZED = auto()
class AlarmClock:
"""An alarm clock that remembers its own settings."""
def __init__(self, alarm_time: time, snooze_minutes: int = 9) -> None:
self.alarm_time = alarm_time
self.snooze_minutes = snooze_minutes
self.state = AlarmState.OFF
self.snooze_count = 0
self._next_ring: datetime | None = None
def turn_on(self, today: date) -> None:
self.state = AlarmState.ON
self.snooze_count = 0
self._next_ring = datetime.combine(today, self.alarm_time)
def turn_off(self) -> None:
self.state = AlarmState.OFF
self._next_ring = None
def tick(self, now: datetime) -> None:
"""Start ringing once the next ring time arrives."""
waiting = self.state in (AlarmState.ON, AlarmState.SNOOZED)
if waiting and now >= self._next_ring:
self.state = AlarmState.RINGING
print("Wake up! Wake up!")
def snooze(self, now: datetime) -> None:
if self.state is AlarmState.RINGING:
self.snooze_count += 1
self.state = AlarmState.SNOOZED
self._next_ring = now + timedelta(minutes=self.snooze_minutes)
def stop(self) -> None:
if self.state is AlarmState.RINGING:
print(f"I am up now! (snoozed {self.snooze_count} times)")
self.turn_off()And the same morning as the original post, with two snoozes:
today = date.today()
clock = AlarmClock(alarm_time=time(6, 30))
clock.turn_on(today)
ring = datetime.combine(today, time(6, 30))
clock.tick(ring) # Wake up! Wake up!
clock.snooze(ring) # rings again 9 minutes later
ring += timedelta(minutes=9)
clock.tick(ring) # Wake up! Wake up!
clock.snooze(ring)
ring += timedelta(minutes=9)
clock.tick(ring) # Wake up! Wake up!
clock.stop() # I am up now! (snoozed 2 times)
print(clock.state) # AlarmState.OFFEvery value the clock needs lives on the instance, created in __init__. The Python tutorial warns about the alternative: a mutable value declared on the class itself, such as a list, is shared by every instance. If you made two clocks, you’d want two separate snooze counts.
Passing now in, rather than reading the system clock inside the methods, keeps the class easy to test. You can run a whole morning in milliseconds.
What is encapsulation, and does Python enforce it?
Encapsulation means the object manages its own state and the rest of the program goes through its methods. Python doesn’t enforce it. A leading underscore, like _next_ring, tells other developers the attribute is internal.
The point is protecting the rules. If any code could set state to RINGING without setting a ring time, the clock could end up in a state that makes no sense. Keeping changes inside snooze() and stop() means the rules live in one place.
The Python tutorial is direct about this: truly private instance variables don’t exist in Python, and data hiding is based on convention. PEP 8 says to use one leading underscore for non-public methods and instance variables. Two leading underscores trigger name mangling, which exists to avoid clashes with subclasses, so it isn’t a security feature either.
Should you use inheritance or composition?
Use inheritance when the new class really is a more specific kind of the old one. Use composition, where an object holds other objects, when it simply has a part. In practice composition is the safer default in many cases, because it’s easier to change later.
My original post said you inherited behaviours from your friends and family. That mixes things up. Inheritance in OOP is a relationship between classes, set when you write the code: a TravelAlarmClock could inherit from AlarmClock because a travel alarm clock is an alarm clock. You don’t pick up methods from the people around you at runtime. Habits you learn from family are closer to state your instance gained over time.
Inheritance gets awkward when you use it for parts. A radio alarm clock is an alarm clock that has a radio, and a projection clock has a projector. Make a subclass for each and you soon need a radio projection clock. Composition handles that by giving the clock a sound source:
class Buzzer:
def sound(self) -> None:
print("Wake up! Wake up!")
class Radio:
def __init__(self, station: str) -> None:
self.station = station
def sound(self) -> None:
print(f"Playing {self.station}")
class AlarmClock:
def __init__(self, alarm_time: time, sounder=None) -> None:
self.alarm_time = alarm_time
self.sounder = sounder or Buzzer()
# ...the rest as before, and tick() calls self.sounder.sound()
bedside = AlarmClock(time(6, 30), sounder=Radio("the jazz station"))Swapping the buzzer for a radio needs no new class. The advice to favour object composition over class inheritance is usually traced to Design Patterns by Gamma, Helm, Johnson and Vlissides. Treat it as a default rather than a rule. Inheritance is still the right tool for a genuine is-a relationship, and frameworks often expect you to subclass their base classes. Keeping each class focused on one job helps either way, which I cover in single responsibility and open/closed.
Does everything need to be a class?
No. Classes earn their place when data and the behaviour that changes it belong together, like the alarm clock. For a calculation that takes inputs and returns a result, a plain function in a module is simpler and just as Pythonic.
Beginners who discover OOP often wrap everything in a class, including code with no state to keep. A class whose only method is run() is usually a function in disguise. Python modules already group related functions, and functions are easier to read, test and reuse when they don’t depend on hidden state.
There’s also a middle ground. If you mostly want a container for related values, a dataclass generates __init__, a readable repr and equality comparison for you, so you write the fields and skip the boilerplate.
Thinking in objects is still worth learning, even if you end up writing mostly functions. It changes how you read other people’s code, and it gives you words for design decisions. If you’re learning this with an AI assistant, ask it to quiz you on the alarm clock rather than writing the class for you. I explain why in how to use AI to learn without offloading the thinking.
Sources
Checked in November against the Python classes tutorial, the enum and dataclasses documentation, PEP 8, and the composition over inheritance reference. The alarm clock, its states and the two-snooze morning come from my original post; the refreshed code and table are mine, and the code was run on Python 3.
Short answers
What is the difference between a class and an object?
A class is the blueprint that describes a kind of thing. An object, or instance, is one specific thing created from it with its own state. AlarmClock is the class, and the clock on your nightstand set for 6:30 is an instance.
What should an object contain?
State and behaviour. State is the data the object remembers, such as an alarm time and a snooze count. Behaviour is the methods that read or change that state, such as snooze() and stop(). A class whose methods only print messages, without changing anything, is missing half of that.
Should I use inheritance or composition?
Use inheritance when the new class is a more specific kind of the old one, such as a travel alarm clock being an alarm clock. Use composition when an object has a part, such as an alarm clock having a radio. Composition is the safer default in many cases because parts can be swapped without new subclasses.
Does everything in Python need to be a class?
No. Use a class when data and the behaviour that changes it belong together. For a calculation that takes inputs and returns a result, a plain function in a module is simpler. A dataclass is a good middle ground when you mostly need a container for related values.
Model the next thing you touch
Pick an object on your desk, write down three things it remembers and three things it does, and turn that into a class with real state. Then ask whether a function would have done the job.