Stage 02 · Lesson 08/15

Programming & Python · Lesson 08

Objects & Classes

Est. 35–45 min

Try it · Python in your browser

Run this lesson's example (sensor_class.py), change a number, run it again.

Why

Why objects bundle state and behavior

By the end you will write a tiny class with __init__, methods, and instance attributes — enough for a sensor stub.

Concept

The big idea: class = blueprint, object = instance

  • class Name: defines a blueprint.
  • __init__ sets initial state (self.name = ...).
  • Methods take self as first parameter.
  • Instance: front = DistanceSensor("front").

How it works

How it actually works, step by step

  1. Name the thing

    Sensor, driver, buffer — noun first.

  2. List state

    What must be remembered between calls?

  3. List actions

    read, reset, is_close…

  4. Code __init__ + methods

    Keep methods short; return values with units in names.

Visual

Visualise it: command console as object calls

Imagine each command as a method on a driver object.

Interactive · Robot command console

Commands (Python-like):
  drive_forward(cm=20)
  turn_left(deg=90)
  turn_right(deg=90)
  stop()
  status()
  • # robot console ready — type a command

Code lab

Code lab: DistanceSensor

sensor_class.py · Python
#!/usr/bin/env python3
"""Tiny sensor class — state + methods."""

class DistanceSensor:
    def __init__(self, name: str, offset_cm: float = 0.0):
        self.name = name
        self.offset_cm = offset_cm
        self.last_cm = None

    def read(self, raw_cm: float) -> float:
        self.last_cm = raw_cm + self.offset_cm
        return self.last_cm

    def is_close(self, threshold_cm: float = 20.0) -> bool:
        if self.last_cm is None:
            return False
        return self.last_cm < threshold_cm

front = DistanceSensor("front", offset_cm=0.5)
print(f"{front.name} reading = {front.read(17.0)} cm")
print(f"close? {front.is_close(20)}")
print(f"close@15? {front.is_close(15)}")

Expected output

front reading = 17.5 cm
close? True
close@15? False

Real world

Where classes help in the lab

  • Hardware drivers wrap serial protocols.
  • Filters keep EMA state.
  • Controllers hold last command + limits.

Mistakes

Common mistakes and confusions

Hardware & safety

Hardware lab and safety notes

One class per real part. Give each HC-SR04 on your robot its own DistanceSensor object — front and back — each with its own offset (the sensor face is rarely at the robot's edge).

  • Measure the offset: tape distance from the sensor face to the robot's front edge.
  • Two objects, one class: front = DistanceSensor("front", 0.5), back = DistanceSensor("back", -1.0).
  • Each object keeps its own last_cm.
HC-SR04 ultrasonic sensor module
One class, many sensors — each HC-SR04 becomes its own object.Photo: SparkFun Electronics · CC BY 2.0 · Source: Wikimedia Commons · resized, converted to WebP

Debugging

Debugging: when it doesn’t work

Symptom → likely cause → fix
SymptomLikely causeFix
TypeError: read() takes 1 positional argument but 2 were givenMissing self in the methodFirst parameter must be self
NameError: name 'last_cm' is not definedUsed last_cm instead of self.last_cmUse self. for state
is_close() is False before any readlast_cm is None at startThat is safe by design — call read() first
Both sensors show the same valueShared class attributeSet state in __init__ with self.
NoteRead the last line of a Python error first — it names the problem — then the line number above it. Change one thing at a time and re-run.

Think

Think about it

Think

Why store last_cm on the object instead of a global?

Experiment

Try it in the lab: class sketch

Experiment

Class sketch

  1. Run sensor_class.py; confirm reading 17.5 with offset 0.5.
  2. Add a second sensor "left" with different offset.
  3. Sketch on paper: attributes vs methods for a BatteryMonitor.

Interactive · Robot command console

Commands (Python-like):
  drive_forward(cm=20)
  turn_left(deg=90)
  turn_right(deg=90)
  stop()
  status()
  • # robot console ready — type a command

Knowledge check

Check your understanding

Knowledge check

1. An object is…

2. __init__ is for…

3. In the lab, front.read(17.0) returned…

4. self refers to…

5. is_close before any read should…

Practice quiz

Loading practice quiz…

Coding practice

Loading coding exercises…

Mini assignment

Hands-on assignment

Mini assignment

Mini class map

Implement DistanceSensor (or BatteryMonitor) with __init__, one update method, one query method.

Deliverables

  • sensor_custom.py
  • 2 instance demo printout

Do this, step by step

  1. Run sensor_class.py: 17.0 + 0.5 = 17.5 cm, close at 20 is True, at 15 is False.
  2. Create a second sensor back with offset −1.0 and read 30.0.
  3. Add a method reset() that sets last_cm back to None.
  4. Write sensor_custom.py (DistanceSensor or BatteryMonitor) with a 2-instance demo.

Stuck? Hints, one at a time

NoteTry the task first. Read one hint, try again, and only then read the next one.
  1. Hint 1: back.read(30.0) returns 29.0.
  2. Hint 2: def reset(self): self.last_cm = None.
  3. Hint 3: BatteryMonitor idea: state last_v, method update(v), query is_low(threshold_v=10.5).

Challenges (pick by level)

  • 🟢 Easy: Add a __repr__ that prints the name and last reading.
  • 🟡 Medium: Keep a list of the last 5 readings inside the object.
  • 🟠 Hard: Write a Robot class that owns two sensors and has nearest_cm().

Next step

Next, Lesson 9: Modules, Packages & Environments. Related: ROS 2 nodes are classes too, in Stage 10 — ROS 2.

Sources

Self-attested for now — keep artifacts in your lab notebook.

Complete

Today's goal

0 of 1 done today

0-day streak
Daily goal:lessons, quizzes or assignments a day

Mark this lesson complete when you have worked the experiment, knowledge check, and assignment (even roughly).

Stuck somewhere?

Ask a doubt about this lesson

Saved with this lesson's id and your email so we can reply. Privacy · or email contact@aihubstation.in