TactivergeLite

Lite / Intelligent Robotic Systems / Week 2

One blueprint, many sensors

A robot has six identical range sensors, each with its own offset and its own readings. Do you write six sets of variables, or one blueprint?

About 40 min · 3 goals · Checked by automated tests · Full interactive version

Why should I care?

Engineering software is full of things that come in many copies: sensors, motors, parts, waypoints. A class describes the kind of thing once; each object is one real copy with its own state. That keeps six sensors from accidentally sharing one list of readings.

Predict

A class puts readings = [] on the class body instead of inside __init__. You record 50 cm on the front sensor. What does the rear sensor's readings list contain?

  1. [] (it is empty)
  2. [52] (the front sensor's reading)
  3. An error
Guess first, then reveal

The front reading! Both objects look up readings on the class, and there is only one list there. Mutable attributes that should belong to each object must be created in __init__ with self.readings = [].

Discover

Record a few readings on front and rear, then compare vars(front) and vars(rear). Call rear.mean() before it has readings and read the error. Now tick the bug toggle and record on front only: what happened to rear?

What the interactive shows (text version)

The inspector shows a RangeSensor class with a front sensor (offset 2 cm) and a rear sensor (offset −1 cm). Recording 50 cm on the front stores 52 in front's own list only. With the bug toggle on, readings live on the class, so the same 52 appears in both sensors' readings.

You can also open the interactive on the full site when you have a faster connection.

Watch (optional)

Watch for: Watch what self refers to inside __init__, and how each new instance gets its own attribute values.

Builds a class step by step, so you can see what __init__ and self actually do for each new object.

“Python OOP Tutorial 1: Classes and Instances” by Corey Schafer (opens YouTube; streaming video uses a lot of data)

The video is optional. Everything you need is in this lesson's text.

Understand

Class, instance, self

class RangeSensor: defines a new type. front = RangeSensor("front", 2) calls __init__ to build one instance. Inside each method, self is the particular object the method was called on, so self.readings means this sensor's readings.

Attributes live on the object

Assigning self.offset_cm = offset_cm stores a value on that one object; vars(front) shows them. Python looks up an attribute on the object first, then on its class. Constants that every instance shares, like unit = "cm", can sit on the class.

The shared-list trap

A list (or dict) written in the class body exists once, for every instance. Appending through self.readings changes that one shared list, so every sensor sees every reading. Create mutable state inside __init__ so each object gets its own.

Explain it another way

Intuitive

A class is like a part drawing; instances are the parts made from it. Every bracket made from one drawing has the same shape, but each has its own serial number and its own scratches.

Technical

Instances store attributes in a per-object namespace (obj.__dict__). Attribute lookup checks the instance, then the class, then base classes. A method call front.record(50) is shorthand for RangeSensor.record(front, 50), which is where self comes from.

Applied

Robot drivers commonly define one class per device type (an IMU, a lidar, a motor controller) and create one object per physical device, each holding its own port, calibration and latest data.

Worked example 1

Model a range sensor with a calibration offset, record readings and report their mean.

class RangeSensor:
    unit = "cm"                      # shared by every sensor

    def __init__(self, name, offset_cm):
        self.name = name
        self.offset_cm = offset_cm
        self.readings = []           # one list per sensor

    def record(self, raw_cm):
        self.readings.append(raw_cm + self.offset_cm)

    def mean(self):
        if not self.readings:
            raise ValueError(f"{self.name} has no readings yet")
        return sum(self.readings) / len(self.readings)


front = RangeSensor("front", 2)
rear = RangeSensor("rear", -1)
front.record(50)
front.record(54)
rear.record(80)
print(front.mean(), rear.mean())     # 54.0 79.0
print(vars(rear))                    # {'name': 'rear', 'offset_cm': -1, 'readings': [79]}

Common mix-ups

Practice

Practice, not a test. Answers are checked on our server; a wrong answer gets a hint and another try. Nothing is saved.

cm

Practice 2. Inside record(self, raw_cm), what is self when you call rear.record(80)?
Practice 3. Which class definition gives each sensor its own readings list?
Practice 4. RangeSensor.unit = "cm" is a class attribute. After front = RangeSensor('front', 2), what is front.unit?
Practice 5. rear = RangeSensor('rear', -1); rear.mean() is called before any readings. With the worked example's code, what happens?

Apply it

Write a Part class for a stores inventory with attributes part_no, description, mass_g and quantity, a method total_mass_kg() and a method withdraw(n) that refuses (raises ValueError) to go below zero. Create three parts and print the total mass of everything in stock.

Reflect

Where in your own code have you used several parallel lists (names, offsets, readings) that would be clearer as one list of objects?

Write your answer on paper or in your own notes. Lite never stores what you write.

Go further

← Tests that catch you before the robot doesObjects that guard their own limits →