Records as structured objects

A lab generator has voltage, current and status. In full Python you may write a class. Here we model an object as a dictionary plus functions that take that record — the same idea as methods, visible on one screen. Classes in Advanced (and in real pygame Sprites) are this idea with nicer syntax.

Lab motor

Group fields; pass the whole record.

You will be able to

  • Group fields in one dict
  • Write functions that take the whole record

Behaviour next to data

power(device) reads fields from one argument. A later class Device with a .power() method is the same design. Start with dicts until the fields stabilize, then graduate to classes if you need many instances with shared behaviour.

Passing the whole record beats passing volts, amps, ok as three separate arguments that get out of order.

Why not five lists?

volts = [12, 5], amps = [2, 1], names = ["motor", "lamp"] will desynchronise the first time you sort one list. A list of records cannot lose a field on one device without you noticing — the dict is either complete or missing a key.

JSON, SQLite rows and pandas records are all this idea. pygame sprites are this idea with a rectangle attached. Learn to pass the whole object.

Words that matter

Record
A dict (or class instance) that groups related fields.

Common mistakes

Avoid: Five parallel lists for five fields.

Do this: One list of records.

Example program — DC motor snapshot

Functions receive the whole device.

Python sandboxlesson://workspace
console

Edit the example, press Run, then Build if you want a compile check.

build

Press Build to compile.

Your turn — Battery percent helper

def percent(bat) returns bat["left"] * 100 / bat["full"]. Print percent of {left: 40, full: 80} as 50.

Python sandboxlesson://workspace
console

Edit the example, press Run, then Build if you want a compile check.

build

Press Build to compile.

Self-assessment

Check your understanding before you mark the lesson complete.

1. Passing a dict into a function lets you…

Progress is stored in a browser cookie on this device.