Skip to the workspace
Pebellslearn by building
Objects  ›  Lesson

What Is OOP?

Object Oriented Programming 18 minObject-oriented programming groups an object’s state with the methods that operate on that state.

Object-oriented programming groups an object’s state with the methods that operate on that state.

Compare a plain-data design with an object and decide which responsibilities and rules belong together.

You can already pass a dictionary into a function. Now several thermostats must each remember a temperature and apply the same adjustment rule. A class gives that data and those operations one name; each object is a particular thermostat. Follow what changes after each call, then decide what this organisation helps with and what it still leaves exposed.

Loose data and loose functions on the left, with nothing stopping a function-less write to balance; an Account object on the right where the front door to balance is a method that can refuse

A thermostat as a plain dict

A thermostat should never be set above 35°C. The obvious first version is a dict plus a function that checks before it writes:

python

That works — as long as everyone remembers to call set_temp. Nothing stops a shortcut:

What does this print?
def set_temp(thermostat, temp):
    if 0 <= temp <= 35:
        thermostat["temp"] = temp

office = {"temp": 20}
set_temp(office, 22)
office["temp"] = 999          # a shortcut, somewhere else in the file
print(office)

The function accepts a dictionary, but ordinary dictionary writes do not call that function. The useful design question is therefore: which operations should the rest of the program use to change the temperature? A class lets us put those operations on the object itself. It will not automatically make direct writes impossible.

Preparing this topic’s interactive investigation…

The same thermostat as an object

The indented def statements below define methods: functions reached through an object, such as office.set_temp(...). Thermostat() creates an instance and runs its __init__ setup. In these methods, self names the instance receiving the call; self.temp is that object's temperature attribute.

This version also deliberately changes the policy: an out-of-range request is clamped to the nearest permitted boundary instead of being ignored.

python

office.set_temp(999) stores 35; the separate print reads that stored value. The method has no return, so the call itself returns None. This distinction between a changed object and a returned result is the same one you met in functions.

Two calls to Thermostat(...) below create two distinct instances. Changing the integer temperature attribute on one leaves the other alone:

What does this print?
class Thermostat:
    def __init__(self, temp=20):
        self.temp = temp

    def set_temp(self, temp):
        self.temp = max(0, min(35, temp))

office = Thermostat()
lab = Thermostat(15)
office.set_temp(28)
print(lab.temp)

Track one object across several calls

An object carries state: values that remain available between calls. The parameters of each method call are temporary; the temperature stored on the thermostat survives that call. Here is the entire state change for one office:

Statement Temperature afterwards Reason
office = Thermostat(20) 20 Setup stores the starting value.
office.set_temp(28) 28 The request is already in range.
office.set_temp(999) 35 The upper limit wins.
office.set_temp(-4) 0 The lower limit wins.

Now insert control_panel = office before the calls. It does not build another thermostat: both names refer to the same one. Reading control_panel.temp therefore shows the updates. Use Thermostat(...) again when you actually need another instance. The next lesson follows this name-to-object relationship more closely.

The class still has two bypasses: office.temp = 999 writes directly, and Thermostat(999) stores an unchecked starting value. Locate those assignments in the source before reading on. A rule holds only on the paths that apply it; adding class does not insert validation into every assignment.

For an independent check, add a reset() operation that restores 20. Starting from 30, setting 999, then resetting should finish at 20; resetting a second time should leave it there. Decide whether reset should assign directly or call set_temp(20), and explain which choice keeps the clamp in one place.

A fleet of thermostats

Because every Thermostat carries the same shape, a list of them can be treated uniformly — a loop doesn't need to know how many there are or care about each one's history:

python

The old habit is still tempting, though — reach in and set the attribute instead of calling the method that guards it:

broken — fix it

One reading comes back an impossible 500°. Route it through set_temp instead of assigning temp directly.

What the next four lessons add

A class alone only buys you one place the rule lives. Four more ideas build on that, each solving a problem this lesson's Thermostat already hints at:

  • Encapsulation — design a public way to read and change state, with checks on those operations. Internal attributes remain accessible; a convention is not a security boundary.
  • Inheritance — a SmartThermostat that does everything Thermostat does, plus a schedule, without copying set_temp.
  • Polymorphism — the fleet loop above already calls .is_comfortable() without asking what kind of thing it's talking to; later lessons lean on that on purpose.
  • Abstraction — state the common operations. An abstract base class can reject an incomplete subclass at creation; behavior still needs examples and tests.

Python doesn't force object-oriented style. A script with three functions and a dict is often the right size for the job. Reach for a class once you notice the same shape repeating — a name, some state, a rule for changing it — for more than one instance of a thing.

Quick practice

What happens when you run this?
class Thermostat:
    def __init__(self, temp=20):
        self.temp = temp
    def set_temp(self, temp):
        self.temp = max(0, min(35, temp))

t = Thermostat          # forgot the ()
t.set_temp(5)
What does this print?
class Thermostat:
    def __init__(self, temp=20):
        self.temp = temp
    def set_temp(self, temp):
        self.temp = max(0, min(35, temp))

t = Thermostat()
t.temp = 999
print(t.temp)
broken — fix itTypeError

Run it and read the error. Then fix the method's parameters.


🎯 Your turn

Define a Thermostat class with __init__(self, start=20) storing self.temp, and adjust(self, delta) that changes temp by delta but clamps it to 0..35 (never lower, never higher). Then write final_temp(start, deltas): open a Thermostat at start, apply each delta in deltas in order, and return the final temp.

  • final_temp(20, [5, 5]) → 30
  • final_temp(20, [-50]) → 0
  • final_temp(20, [100]) → 35

Hint: self.temp = max(0, min(35, self.temp + delta)) inside adjust; build one Thermostat, loop the deltas calling .adjust(d), then return .temp.

Press ▶ Run and hit ✓ Check. ✅

Your task
Define a Thermostat class with __init__(self, start=20) storing self.temp, and adjust(self, delta) that changes temp by delta but clamps it to 0..35. Then build final_temp(start, deltas): open a Thermostat at start, apply each delta in order, and return the final temp. Example: final_temp(20, [5, 5]) -> 30.

Practice — level up

0/5 solved

Solve each in its own editor — Run to try, Check to grade. Stuck? Reveal a Hint, or the full Solution + walkthrough.

Warm-upA switch that remembers

Define a Switch class starting off (self.on = False) with a flip() method that toggles it. Write flips_result(n) that creates a Switch, flips it n times, and returns whether it ends up on.

classesstate
DrillA tally that never forgets

Define a Tally class starting at 0 with an add(n=1) method that adds n to the running count. Write total_after(adds) that creates a Tally, calls add once per number in adds, and returns the final count.

classesstatemethods
BuildA stack that won't crash empty

Define a Stack class holding self.items = [], with push(item), pop() (removes and returns the top, or None if empty — never crashes) and peek() (returns the top without removing it, or None). Write stack_ops(ops): each op is a string, "push 5", "pop" or "peek". Return a list of the results from every pop/peek (skip push, it has no output).

classesstateguards
BossA machine that refuses short change

Define a VendingMachine class taking a price and a buy(amount) method: "dispensed" if amount >= price, else f"insert more: {shortfall:.2f}" where shortfall is price - amount rounded to 2 decimals. Write vend_results(price, payments) that creates one VendingMachine and returns the result of buy for each payment in order.

classesstateguardsf-strings
CapstoneShapes that each know their own area

Define Square (side) and Circle (radius), each with an area(self) method (math.pi * radius ** 2 for the circle). Write total_area(specs) where specs is a list of [kind, measurement] pairs like ["square", 3] or ["circle", 2]. Build the matching object for each spec, then return the sum of every .area(), rounded to 2 decimals. Once the objects exist, the summing itself must not check kind — only call .area().

classespolymorphismarithmetic
Project context and further resources
final_temp.py
Call the function you wrote — just like your app's frontend would. Edit the inputs and hit Call.
final_temp(start, deltas) → intOpen a Thermostat at start, apply each delta in order, return the final (clamped) temp.
try:
returned
Press Run to execute your code.
Press Check to run the tests for this lesson.
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.