Skip to content
Tactiverge

School/○ Innovator/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

1.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.

  • ◇ Define a class with __init__, attributes and methods to model a sensor.
  • ◇ Create several instances and explain why each keeps its own attribute values.
  • ◇ Tell instance attributes from class attributes and avoid the shared-list bug.

2.Watch

→ 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.

Length: see YouTube · captions on YouTube · source

Nothing loads from YouTube until you press play.

The video is optional: everything you need is also in the lesson text and the interactive.

3.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?

Guess first. Being wrong here is how the surprise works.

4.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?

Loading the interactive…

Can't use the interactive? Read a description instead

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.

5.Checkpoint: guided practice

Check what you just discovered before going on. Hints appear after a wrong answer.

Practice 1

Using RangeSensor from the worked example, s = RangeSensor('left', 3); s.record(40); s.record(46). What does s.mean() return?

cm

Practice 2

Inside record(self, raw_cm), what is self when you call rear.record(80)?

6.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

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.

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

  • self is a keyword that means the class.
    ✓ self is just the conventional name for the first parameter, which receives the instance the method was called on.
  • Each object gets its own copy of every class attribute.
    ✓ Class attributes are shared. Only attributes assigned on self belong to one object.

7.Practice on your own

Practice, not a test. Wrong answers get a hint and another try.

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?

8.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.

9.Reflect

10.Go further

Concepts: Classes and objects