CSSE1001 — Week 8 Notes

Dunder (Magic) Methods

Lecture 8A. See csse1001 for course logistics and python-dunder-methods for the full reference on __init__, __str__, __repr__, and operator overloading. Diagrams below follow csse1001-diagram-notation.

Outline

  • Recap: class vs. object
  • Exercise: a Clicker tally counter
  • Underscores: anonymous variables, private variables, and dunder names
  • Magic methods: __init__, __str__, __repr__, __eq__, __add__, __sub__
  • Overloadable operator tables (binary, unary, comparison)
  • Instance variables vs. class variables

Class vs. object

A class collects attributes on one side and methods on the other, and every object is one instantiation of it (Figure 1).

Figure 1: The class as blueprint: the attributes it declares (left, purple outline), the methods it provides (right, magenta outline), and the objects instantiated from it below. The arrows run downward, class to instance. Inheritance arrows run the other way, up into the parent.

Aspect Class Object
Meaning Blueprint/template for creating objects Instance of a class with real data
Represents General concept or idea Concrete entity based on a class
Defined by class keyword Instantiating a class
Example class Animal: my_animal = Animal()
Memory usage No direct memory for data Allocates memory for attributes
Purpose Describes structure and behaviour Performs actions and stores data
Analogy House blueprint Actual built house

Exercise: Clicker

Create an object called Clicker that simulates the functionality of a mechanical hand tally counter.

The class this produces is used again under Instance vs. class variables.

Underscores

Python overloads the underscore with several distinct meanings (not an exhaustive list):

  1. As anonymous variables, e.g. for _ in [1, 2, 3]: or x, _, z = (1, 2, 3).
  2. For giving special meaning to functions and names:
    • _private variables — a leading single underscore (convention only).
    • __names__ — reserved for Python’s magic/dunder methods, like __init__().

III: Magic (overloading built-in functions)

Magic is part III of the OOP material. Parts I (structure) and II (methods) are in Lecture 7C (2025-09-09-object-oriented-programming).

We can create a new type, Fraction, with:

  • Data attributes: numerator, denominator.
  • Methods: arithmetic operations (add, eq, sub) to work with +, ==, -; and a print-friendly representation.

Initialiser

Runs when the object is instantiated (created):

class Fraction():
    def __init__(self, numer: int, denom: int) -> None:
        self._numer = numer
        self._denom = denom

String representation (__str__)

Says what to display when printing the object:

>>> p = Fraction(2, 3)
>>> print(p)
<__main__.Fraction object at 0x7f95c625e9d0>

Without a __str__, printing an object just shows its default memory-address representation. Defining one fixes this:

>>> class Fraction():
...     def __str__(self) -> str:
...         return f"A fraction: {self._numer} / {self._denom}"   # must return a string
>>> p = Fraction(2, 3)
>>> print(p)
A fraction: 2 / 3

__str__ must return a string. Returning anything else is a TypeError raised at print time, not at definition time: nothing checks the return annotation when the def is executed.

Representation (__repr__)

The representation of an object is what Python displays for it in the console, and should be enough information to re-instantiate the object:

>>> class Fraction():
...     def __repr__(self) -> str:
...         return f"{self._numer} / {self._denom}"
>>> p = Fraction(2, 3)
>>> p
2 / 3

This is equivalent to calling print(repr(p)) or directly invoking print(p.__repr__()) — but we don’t manually invoke these methods; Python does.

__repr__ vs. __str__

  • __repr__ is meant to be used by the programmer:
    • Unambiguous — it should clearly describe the object.

    • Meant for debugging, logging, and development, not end-users.

    • Its output should, if possible, be a valid Python expression that could recreate the object when passed to eval():

      >>> u
      Vector2D(x=2, y=3)
      >>> print(u)
      2D Vector: (2, 3) --- length: 3.605551275463989
      >>> u_copy = eval(repr(u))
      >>> u_copy
      Vector2D(x=2, y=3)

      The round trip is u → repr() → "Vector2D(x=2, y=3)" → eval() → a second object that prints the same way. (The transcript shows the two reprs matching; it never evaluates u == u_copy.)

  • __str__ is meant for pretty prints (a user-friendly string, printed for the user).

In the transcript above, >>> u and >>> print(u) produce different output from the same object: the first goes through __repr__, the second through __str__.

Equality (__eq__)

We can specify that objects are equal for reasons other than sharing a memory location:

>>> class Fraction():
...     def __eq__(self, other) -> bool:   # note the use of 'other'
...         a, b = self._numer, self._denom
...         c, d = other._numer, other._denom
...         return a*d == b*c
>>> p = Fraction(4, 6)
>>> q = Fraction(2, 3)
>>> p == q
True

4/6 == 2/3 because the method cross-multiplies (4·3 == 6·2) rather than comparing the stored pairs. The second parameter is named other, and the convention holds for every binary dunder, which receives the left operand as self and the right one as other.

Addition (__add__)

Instructs Python on how to add two objects together:

>>> from __future__ import annotations   # for the class' own type hint
>>> class Fraction():
...     def __add__(self, other) -> Fraction:
...         a, b = self._numer, self._denom
...         c, d = other._numer, other._denom
...         return Fraction(a*d + c*b, b*d)
>>> p = Fraction(2, 3)
>>> q = Fraction(1, 2)
>>> p + q
7 / 6

The from __future__ import annotations line is there so that -> Fraction can name the class inside its own body, before the class object exists.

The last line shows 7 / 6 only because __repr__ is in the class too: __add__ builds a new Fraction and the console then displays it through __repr__. Two magic methods are cooperating in one line of output. Read literally, though, each of these transcripts re-enters class Fraction(): from scratch at the prompt, so the class here has only __add__. With no __init__, p = Fraction(2, 3) would fail on line 7 with TypeError: Fraction() takes no arguments, long before p + q was reached. The transcripts only work if you read the class as accumulating from one to the next.

Subtraction (__neg__, __sub__)

>>> from __future__ import annotations
>>> class Fraction():
...     def __neg__(self) -> Fraction:
...         return Fraction(-self._numer, self._denom)
...     def __sub__(self, other) -> Fraction:
...         return self + -other
>>> p = Fraction(2, 3)
>>> q = Fraction(1, 2)
>>> p - q
1 / 6

__sub__ is defined entirely in terms of __add__ and __neg__: p - q becomes p + (-q) = Fraction(2·2 + (−1)·3, 3·2) = Fraction(1, 6).

The negation method is __neg__, not __neq__. Spelled def __neq__(self), the class would define an unused __neq__ and leave -other inside __sub__ unsupported, so p - q would raise TypeError: bad operand type for unary -: 'Fraction' rather than printing 1 / 6.

What “magic” actually means

Every method above is invoked for you. You write the ordinary Python in the left column of Figure 2; the interpreter turns it into the call on the right. The one place above where a dunder method is called by name is print(p.__repr__()). Even that is not an operator being invoked, and it is the equivalent you don’t type. Dunder names do appear elsewhere, in __main__ inside the default repr, in the from __future__ import annotations import, in the three operator tables below and in the wording of the Vector and Currency exercises, but never as a call you write.

Figure 2: What ‘magic’ means: you write the left-hand column, Python calls the right-hand one. We don’t manually invoke these methods; Python is the one doing it. One nuance the arrows flatten: __init__ really runs on the freshly created object before the name p is bound to it.

Overloadable operators

Binary operator Magic method
+ __add__
- __sub__
* __mul__
** __pow__
// __floordiv__
/ __truediv__
Unary operator Magic method
- __neg__
abs __abs__
~ __invert__
Comparison Magic method
< __lt__
<= __le__
== __eq__
!= __ne__
> __gt__
>= __ge__

Instance vs. class variables

The Clicker class for counting clicks:

class Clicker():
    def __init__(self) -> None:
        self._clicks = 0   # each instance has its own

    def click(self) -> None:
        self._clicks += 1

To calculate the number of clicks across all counters, use a class variable:

class Clicker():
    _all_clicks = 0   # every instance has access to this

    def __init__(self) -> None:
        self._clicks = 0

    def click(self) -> None:
        self._clicks += 1        # access instance variable
        Clicker._all_clicks += 1  # access class variable
>>> c = Clicker(); d = Clicker(); e = Clicker()   # semi-colons can be used instead of newlines
>>> c.click(); c.click(); c.click();
>>> d.click(); d.click();
>>> e.click()

>>> (c._clicks, d._clicks, e._clicks)   # bad practice
(3, 2, 1)

>>> (c._all_clicks, d._all_clicks, e._all_clicks)
(6, 6, 6)

>>> Clicker._all_clicks   # you don't even need an instance
6

The (3, 2, 1) against (6, 6, 6) is the whole point: three objects, three private counters, one shared total.

Figure 3: The click counts drawn as a memory picture, in Python Tutor’s idiom. Three instances carry three separate _clicks cells; the single Clicker class object carries one _all_clicks cell, which is why c._all_clicks, d._all_clicks, e._all_clicks and Clicker._all_clicks all read 6.

Figure 3 also explains why click writes Clicker._all_clicks += 1 rather than self._all_clicks += 1: the class variable lives on the class object, so the class object is what has to be updated. See python-dunder-methods for what goes wrong if you write it the other way.

Summary

Classes (or objects) are like functions that maintain their state even after returning. Classes have attributes and methods, and provide a public interface — through setters and getters — for manipulating values considered private to the object.

Exercises

Task (Vectors). + concatenates lists:

>>> [1, 2, 3] + [4, 5, 6]
[1, 2, 3, 4, 5, 6]

Implement a Vector class so that we can do:

>>> x = Vector(1, 2)
>>> y = Vector(3, 4)
>>> x + y
<4, 6>
>>> -x
<-1, -2>

Both output lines come back at a bare prompt, so the <4, 6> format is __repr__’s job, not __str__’s.

Starter code:

class Vector():
    def __init__(self, x: int, y: int):
        self._x, self._y = x, y

    def __add__(self, other):
        ...

    def __neg__(self):
        ...

    def __repr__(self):
        ...

Extension: try creating a Vector class that handles an arbitrary dimension. If two vectors of different sizes are added, __add__ should raise a ValueError.

The Vector2D in the __repr__ vs. __str__ transcript earlier is a related class, with a __repr__ of Vector2D(x=2, y=3) and a __str__ that also reports a length. It is 2D-only, so it is not the arbitrary-dimension extension asked for here. python-dunder-methods has a Vector2D consistent with that transcript.

Task (Currency). Create a class for working with the currencies AUD, EUR, and JPY. Implement the __repr__, __gt__, and __add__ magic methods — you’ll need the dollar/euro/yen symbols, and to do currency conversions when adding different currencies together. Use: 1 AUD is 0.62 EUR; 1 AUD is 79.7 JPY.

Starter code:

class Currency():
    def __init__(self, value: float, currency: str) -> None:
        """ <currency> is one of 'AUD', 'EUR', 'JPY'. """
        self.value = value
        self.currency = currency

    def __repr__(self) -> str:
        ...

    def __add__(self, other) -> object:
        ...

    def __gt__(self, other) -> bool:
        ...

This starter breaks the convention used everywhere else: value and currency are public, where every other class here uses _value-style private attributes.

Task (Greeter). A fully worked example, using a class variable as a shared lookup table:

class Greeter():
    _lang_to_hello = {
        "FR": "Bonjour",
        "AU": "G'Day",
        "DE": "Hallo",
        "CN": "Ni Hao"
    }

    def __init__(self, country: str) -> None:
        self._country = country

    def greet(self) -> str:
        return Greeter._lang_to_hello[self._country]
>>> a = Greeter("FR"); b = Greeter("AU")
>>> c = Greeter("DE"); d = Greeter("CN")
>>> a.greet()
'Bonjour'
>>> b.greet()
"G'Day"
>>> c.greet()
'Hallo'
>>> d.greet()
'Ni Hao'

b.greet() comes back as "G'Day", in double quotes where the other three are in single quotes: that is the repr Python prints for a string containing an apostrophe.

This is the class-variable idea from Figure 3 used for something other than counting: one dictionary, built once on the class object, read by every instance. Four Greeter objects, four _country strings, one _lang_to_hello.

Next: 2025-09-16-representation-invariants (Lecture 8B).

Representation Invariants

Lecture 8B. Course logistics are in csse1001. The full reference on writing and enforcing invariants is python-representation-invariants. Diagrams below follow csse1001-diagram-notation.

Outline

  • What representation invariants are, and why they matter
  • Documenting invariants in docstrings
  • Enforcing invariants with assert and a _check_invariants() helper
  • Encapsulation and avoiding exposed mutable state
  • Worked example: DroneFlight

What are representation invariants?

Representation invariants are conditions or properties that must remain true about the internal state of an object throughout its lifetime (usually enforced during development).

Why do they matter?

  • Discover and prevent bugs and inconsistent behaviour.
  • Simplify the implementation of methods (you can assume a valid starting state).
  • Make code more maintainable and robust.
  • Help detect errors early.
  • Serve as documentation for developers.

Examples

  • A stack’s size must never be negative.
  • A list’s length must equal the number of elements it contains.
  • All elements in a set must be unique.
  • A fraction’s denominator cannot be zero.
  • A date must follow calendar rules (e.g. no 30 Feb).
  • For free/basic X (Twitter) accounts, the standard limit is 280 characters per tweet.

Writing representation invariants

Clearly state invariants in docstrings, underneath a class’s attributes:

class Fraction():
    """Represents a mathematical fraction.

    Representation Invariants:
    - denominator != 0
    - if fraction is zero, it is represented as 0/1
    - if fraction is negative, numerator is negative
    """

Each of these three is a checkable statement about the stored attributes, not a description of what the class is for. The second and third are normalisation rules — they pick one representative out of several possible encodings of the same value (so 0/5 and 1/-2 are not valid internal states even though they name valid numbers).

Enforcing representation invariants

Assertions

Directly check conditions in the initialiser and setter methods, using an assert statement to raise an AssertionError if an assumption isn’t met:

assert <statement that should be true>, "Error message if not True"
  • Assertions can be disabled in production when running Python with optimization (python -O).
  • Assertions are meant to find bugs (e.g. invalid states) during development.
class Fraction():
    def __init__(self, numer: int, denom: int) -> None:
        assert denom != 0, "Denominator cannot be zero."
        assert isinstance(numer, int), "Numerator must be an integer."
        assert isinstance(denom, int), "Denominator must be an integer."

        # Ensure denominator is positive
        if denom < 0:
            numer, denom = -numer, -denom
        self._numer = numer
        self._denom = denom

        # Special case for zero
        if self._numer == 0:
            assert self._denom == 1, "Zero must be 0/1"

Two things about this listing:

  • The sign rule is established, not checked: if denom < 0: numer, denom = -numer, -denom rewrites the arguments so the invariant “if the fraction is negative, the numerator is negative” holds by construction.
  • The zero rule is checked, not established: Fraction(0, 5) passes every earlier assertion, then trips assert self._denom == 1. So a perfectly reasonable-looking call is rejected rather than normalised to 0/1. The two invariants in the same initialiser are enforced by opposite strategies.

Private attributes and encapsulation

  • Use private (_variable) names to discourage direct access.
  • Provide public methods that maintain the invariants.
  • Never expose mutable objects directly:
class Team():
    def __init__(self):
        self._members = []   # internal mutable state

    # classic getter (dangerous!)
    # BAD!
    def get_members(self):
        return self._members

    # instead, return a copy
    # GOOD!
    # def get_members(self):
    #     return list(self._members)  # caller can't modify internal state directly

t = Team()
members = t.get_members()   # gets the actual list inside the class
members.append("Alice")      # modifies it directly!

print(t.get_members())        # ['Alice'] <-- internal state was changed externally

The reason this defeats every assertion you could write is that no method of Team is running when the change happens: get_members has already returned, and the caller then mutates the object Team is still holding, from outside (Figure 4). This is the aliasing problem from 2025-08-18-non-primitive-data arriving inside a class.

Figure 4: Why ‘never expose mutable objects directly’. Top: get_members returns the real list, so t._members and the caller’s members name the same object and the caller’s append mutates the Team without any Team method running. Bottom: list(self._members) hands back a copy, so the append lands where the Team cannot see it. Aliasing is two arrows converging on one object; a copy is two arrows to two objects.

Helper methods

Define a private method (e.g. _check_invariants()) that validates the object’s state, and call it after any state changes:

state change → _check_invariants → valid

When to call _check_invariants():

  • At the end of __init__.
  • At the end of methods that modify object state.
  • At the beginning of methods that rely on invariants being true.
class Fraction():
    def __init__(self, numer: int, denom: int) -> None:
        self._numer = numer
        self._denom = denom
        self._check_invariants()

    def _check_invariants(self) -> None:
        """Verify that representation invariants hold."""
        assert isinstance(self._numer, int), "Numerator must be an integer."
        assert isinstance(self._denom, int), "Denominator must be an integer."
        assert self._denom != 0, "Denominator cannot be zero."
        assert self._denom > 0, "Denominator must be positive."
        if self._numer == 0:
            assert self._denom == 1, "Zero must be 0/1"

Compared with the assertion version above, the centralised version drops the if denom < 0 normalisation and asserts self._denom > 0 instead. Everything is now checked and nothing is fixed up, so Fraction(1, -2) raises here where the earlier version quietly rewrote it to -1/2. That is the trade the pattern makes — one method that says what a valid object looks like, and no hidden repair.

Best practices

  • Document invariants in docstrings.
  • Centralise invariant checking in a single method.
  • Do not expose methods that could violate invariants.
  • Create comprehensive test cases focusing on edge cases (see 2025-09-01-testing).
  • Python’s type hints can express some invariants.
  • Balance strictness with practicality.

Exercise: DroneFlight

You have joined a start-up that records quick test flights for hobby drones. Write a minimal DroneFlight class that always keeps its state valid by enforcing these representation invariants:

  • Drone ID — exactly six alphanumeric characters (e.g. "A1B2C3").
  • Altitude — must stay within 0 m–120 m, the CASA (Civil Aviation Safety Authority) legal ceiling for recreational drones.
  • Battery — an integer percentage in the range 0–100.

Solution

class DroneFlight:
    """
    Model a quick test-flight for a small hobby drone.

    Attributes:
    _id (str) : 6-character alphanumeric flight identifier.
    _altitude (float): Current altitude in metres above launch point.
    _battery (int): Remaining battery charge as a percentage (0-100).

    Representation invariants:
    - _id is a 6-character alphanumeric string
    - 0 ≤ _altitude ≤ 120
    - 0 ≤ _battery ≤ 100
    """

    _ID_LEN = 6         # one place to change if the rule changes
    _MAX_ALT = 120.0    # metres (CASA limit)

    def __init__(self, flight_id: str) -> None:
        self._id = flight_id
        self._altitude = 0.0
        self._battery = 100
        self._check_invariants()

    def _check_invariants(self) -> None:
        assert (
            isinstance(self._id, str)
            and self._id.isalnum()
            and len(self._id) == self._ID_LEN
        ), "ID must be a 6-character alphanumeric string."
        assert 0.0 <= self._altitude <= self._MAX_ALT, "Altitude out of range."
        assert 0 <= self._battery <= 100, "Battery out of range."

    # Getter and setter methods
    def get_flight_id(self) -> str:
        """Return the immutable flight identifier."""
        return self._id

    def get_altitude(self) -> float:
        """Return current altitude in metres."""
        return self._altitude

    def get_battery(self) -> int:
        """Return remaining battery charge (percentage)."""
        return self._battery

    def set_altitude(self, value: float) -> None:
        """Set altitude, clamping to legal ceiling."""
        if not isinstance(value, (int, float)):
            raise TypeError("Altitude must be a number.")
        if not 0.0 <= value <= self._MAX_ALT:
            raise ValueError(f"Altitude must be 0-{self._MAX_ALT} m.")
        self._altitude = float(value)
        self._check_invariants()

    def __repr__(self) -> str:
        return (f"DroneFlight({self._id}, "
                f"alt={self._altitude:.1f} m, bat={self._battery} %)")

    def ascend(self, metres: float) -> None:
        """Climb *metres* metres (cannot exceed the legal ceiling)."""
        if metres < 0:
            raise ValueError("ascend() expects a non-negative distance.")
        self.set_altitude(min(self._altitude + metres, self._MAX_ALT))

    def land(self) -> None:
        """Land the drone and consume 5 % battery."""
        self.set_altitude(0.0)
        self._battery = max(self._battery - 5, 0)
        self._check_invariants()

Three techniques in this solution are the transferable part of the exercise:

  • Class constants for the limits. _ID_LEN and _MAX_ALT are class variables (see 2025-09-16-dunder-methods), so the code enforcing those two limits reads them from a single place: one place to change if the rule changes, as the comment on _ID_LEN says. The class only half keeps the promise, though: the docstring above still spells out 0 ≤ _altitude ≤ 120 in words, and the battery bounds are written literally as 100 in __init__ and 0/100 in _check_invariants() with no constant behind them.
  • assert for bugs, raise for callers. _check_invariants() uses assert — it is looking for a broken implementation, and it is fine for it to vanish under python -O. set_altitude() uses raise TypeError / raise ValueError — it is validating an argument the caller supplied, and that check must run in production. Both appear in the same class, deliberately.
  • Mutation routed through one method. ascend() and land() do not touch self._altitude; they call set_altitude(), so there is exactly one place that can change the altitude and exactly one place the range check has to live. ascend() also clamps with min(..., self._MAX_ALT) before calling, so a legal climb past the ceiling stops at the ceiling instead of raising.
>>> d = DroneFlight("ABC123")
>>> d.ascend(50)
>>> print(d)
DroneFlight(ABC123, alt=50.0 m, bat=100 %)

>>> d.altitude = 200
Caught: Altitude must be 0-120 m.

>>> DroneFlight("BAD!")
Caught: ID must be a 6-character alphanumeric string.

>>> d.land()
DroneFlight(ABC123, alt=0.0 m, bat=95 %)

Figure 5: The DroneFlight demo as a state trace: each accepted call lands the object in a snapshot that satisfies all three documented invariants, and _check_invariants() is what asserts it. The panel on the right gives that method’s three assert conditions, with the class constants replaced by their values (_ID_LEN → 6, _MAX_ALT → 120.0) so the bounds can be read off directly; they are the same three invariants the docstring states in words. The rejected calls below never produce a snapshot at all — the guard fires first, so no invalid state is ever reachable. A green tick is an accepted call and a red cross is a rejected one. The rejected altitude change is drawn as d.set_altitude(200), the call that actually raises, because d.altitude = 200 does not call the setter at all; its message reads 0-120.0 m, which is what the class’s own f-string over _MAX_ALT = 120.0 produces.

The d.altitude = 200 line in the transcript appears to raise a “Caught” error, but as written this class only defines set_altitude() as an ordinary method — it has no @property/@altitude.setter. Plain attribute assignment like d.altitude = 200 doesn’t call set_altitude() at all; it silently creates a brand-new, unrelated altitude attribute (alongside the real _altitude) and raises nothing. To actually trigger the validation, the call has to be d.set_altitude(200) wrapped in a try/except (TypeError, ValueError) as e: print("Caught:", e). The Caught: prefix on both error lines comes from a wrapper of that kind. Constructing DroneFlight("BAD!") is legitimate, though — __init__ really does call _check_invariants(), so an invalid ID genuinely raises an AssertionError there (assuming it’s likewise wrapped in a try/except AssertionError). _check_invariants() would not catch the stray altitude attribute either: it only ever inspects _id, _altitude and _battery.

One further mismatch: _MAX_ALT is 120.0, so the f-string in set_altitude produces "Altitude must be 0-120.0 m.", not the 0-120 m in the transcript. Figure 5 shows the message the listed code would actually produce, with d.altitude = 200 replaced by the set_altitude call that reaches that f-string.

Summary

  • Representation invariants define the valid states of an object.
  • They help catch bugs early and document assumptions (mostly during development time).
  • We can use _check_invariants() to verify invariants, and call it after state changes.
  • Good invariants are specific, testable conditions.

Next: composition and inheritance (Week 9) — 2025-09-23-composition and 2025-09-23-inheritance.

Reference material

CSSE1001 Diagram Notation

This note records the drawing conventions CSSE1001 actually uses, inferred from its own lecture slides. It is the reference that later diagrams in this course should be checked against.

ImportantThis course ships no notation guide

There is no written style or notation standard anywhere in the CSSE1001 materials. The course profile lists no prescribed textbook and no drawing guide; the “Learning resources” section points only to the UQ Library, Blackboard and Ed Lessons. Every convention below is inferred from the drawings themselves, not quoted from a rule.

The three exceptions — places where the slides state a rule in words rather than merely demonstrate one — are the naming conventions (see Naming and capitalisation) and the one figure-source note in 12b. Everything else is observation.

How to read the citations

Decks are cited by their lecture code and PDF page number, e.g. 10a p7 = the UML deck, seventh page of the PDF.

Do not cite the printed footer numbers. They are unreliable: 09a runs 1/14 … 4/39, 5/39, 6/14 … 15/14, 16/15 and then ends on a page footed 14/14 that is actually PDF page 17. Several decks have footer totals that disagree with their own length (11a’s last page reads 14/13). PDF page index is the only stable address.

Colours were sampled from the rendered pages, quantised to 16 levels per channel, so hex values are accurate to roughly ±8 per channel.

What I sampled

248 pages read as images, out of 726 across 25 decks — 17 of the 25 decks. Full text was extracted from all 25 decks plus the course profile, and every deck was scanned for embedded raster images, so the unread decks were checked for figures even where I did not read them.

Deck Pages read
01a history-of-computing 22–33
02a python-memory-model 4–28
03a functions 23–28
03b sequence-selection-and-iteration 2–19
04b non-primitive-data 2–17
07a exceptions 14–21
07b scope 5–19
07c object-oriented-programming 2–19
08a dunder-methods 2–5
08b representation-invariants 5–14
09a composition 1–17 (all)
09b inheritance 1–19 (all)
10a uml 1–14 (all)
10b advanced-inheritance 1–20
11a model-view-controller 1–14 (all)
12a recursion 2–15
12b complexity-and-sorting 2–19

Not read as images: 00-welcome, 01b python-as-a-calculator, 02b primitive-data, 04a while-loops, 05a for-loops, 05b comprehensions, 06a string-methods, 06b file-io. An image-extraction scan across all decks found zero embedded raster images in seven of those eight (00-welcome has six photo pages), and they are typeset in the same LaTeX Beamer template as the decks I did sample. So the risk that they hide an unseen diagram idiom is low but not zero — the eight decks above are the blind spot in this note.

The two slide families

Almost every visual inconsistency in this course traces back to one fact: the decks come from two different production pipelines, and many decks mix both on adjacent pages.

LaTeX Beamer family — serif body text (Computer Modern), ruled code listings with line numbers, coloured named block headings, no raster images. Covers 01b, 02a, 02b, 03a, 03b, 04a, 04b, 05a, 05b, 06a, 06b, and most of 07a/07b/12a/12b.

PowerPoint family — sans-serif labels, filled colour boxes, drop shadows, stock photography, dark-theme code screenshots. Every deck carrying Based on slides from Dr. Azadeh Ghari-Neiat on its title page (07a, 07b, 07c, 08a, 08b, 09a, 09b, 10a, 10b, 11a) contains PowerPoint-family pages.

Consistency: this split holds across the whole semester and is the single most useful thing to know before drawing anything for this course.

Colour palette

These five colours carry meaning and recur across many decks. Everything else is decorative.

Colour Sampled Means Evidence
Dark blue #3030B0 Slide title 10a p4, p7, p10; 09a p12; 10b p10, p19
Magenta #E00080 Defined term, emphasis, the answer 10a p4; 02a p6; 12a p2
Purple #92278F Named block heading; margin annotation 03b p4; 12b p19; 09a p12; 10b p13
Green #109050 (LaTeX) / #00B050 (PPT) A prompt to the student 02a p5; 03b p11; 10a p12; 11a p8
Red #F00000 Warning / failure path 12a p10; 07b p13; 04b p14

Purple #7030A0 is a different purple. It is used only for the UML legend boxes (10a p7, p8, p10, p11) and for the Warning heading in 07b p6. Do not conflate it with the block-heading purple.

Consistency: the blue/magenta/purple/green assignments hold from week 2 (02a) to week 12 (12b). Red is the least consistent — see Inconsistencies.

Named block headings

LaTeX-family slides open a block with a coloured heading on its own line, no box and no rule.

  • Green — a prompt the student is meant to act on: Question (02a p5, 12b p3, p9, p12), Exercise (03b p11, p14; 12b p5, p8, p11, p15; 09b p17; 10a p12; 11a p8), Example (02a p22, p24, p25), Task (07b p17).
  • Magenta italic — the resolution: Answer (02a p6, p7, p8, p9, p23; 12b p18).
  • Purple — a formal or named block: Definition (…) (03b p4, p6, p7, p12; 04b p3; 07c p5; 12b p19), Proposition (12a p13), Base Case / Induction Hypothesis (12a p14), Observe (03b p10), Summary / Next (02a p28, 07a p21, 07b p19), Constants (07b p5), and named algorithms Insertion Sort / Bubble Sort / Merge Sort / Quick Sort (12b p3, p6, p9, p12, p16).

Definition blocks are parenthesised with the term being defined: Definition (Boolean domain), Definition (Predicate), Definition (List), Definition (Complexity).

Consistency: green/magenta/purple hold across at least five decks spanning weeks 2–12. The Warning heading is the exception.

Section divider slides

A section break is a slide bearing one large magenta italic serif word, left-of-centre and high on the page, with a short parenthetical gloss beneath it in small black roman type.

  • Variables — (Named memory locations.) — 02a p14
  • Sequencing — (Order of instructions matters.) — 02a p21
  • Selection — (Controlling program flow.) — 03b p2
  • Lists — (Mutable Ordered Collections.) — 04b p2
  • Memes — (Recursions through meme examples.) — 12a p3

When a deck runs a numbered series of dividers, they take Roman numerals with a colon, and the series continues across decks:

  • I: Structure — (Holding named attributes.) — 07c p8
  • II: Methods — (Object scoped functions.) — 07c p15
  • III: Magic — (Overloading built-in functions.) — 08a p5

Consistency: strong — six plain dividers across four decks, plus a three-part numbered series spanning two decks. One divider (08b p11, Exercise) carries no gloss.

Code listings

Code is by far the most frequently drawn thing in this course, and its presentation is a notation in its own right.

Ruled block. A listing is bounded by a horizontal rule above and below, full text width, with no vertical rules and no background fill. Line numbers run in tiny grey type in the left margin. Code is monospace with visible letter-spacing.

REPL vs. file. The two are distinguished by prompts, not by styling:

  • A REPL transcript uses a magenta >>> prompt for the first line of an input and a magenta ... for continuation lines; output follows on its own line with no prompt (02a p13, p15–p20; 03b p5, p8, p13, p15–p18; 04b p4–p13; 07b p5–p16; 10b p9, p11, p15, p18).
  • A file or definition is shown with line numbers but no prompts at all (04b p15, p16, p17; 08b p6, p9, p13, p14; 09a p10–p14).

Colour inside code. Black is the default. Magenta marks the token or line under discussion — class names being introduced (Battery, Camera, Motor, 09a p10, p11), the lines inherited or overridden (10b p10, p13, p17), the assert keyword (08b p6, p9), the constant being referenced (08b p13, p14). Boolean operators are coloured by identity: and in cyan, or in green, held consistently through 03b p9, p10, p11, p14.

Vertical ellipsis. Elided code is a centred ⋮ on its own line (03a p23) or three stacked full stops (07a p15).

Placeholder metasyntax. Things the student must substitute are written in angle brackets in monospace: <code> and ExceptionName_k (07a p15, p16), <object_variable>.<method>(<parameters>) (07c p16), <statement that should be true> (08b p5). Consistency: three decks.

Annotating code

This is the course’s real “diagram” vocabulary — it annotates listings far more often than it draws figures.

Right-margin note. A short purple italic serif phrase, right-aligned, on the same line as the code it comments on. Sampled #92278F in both 09a p12 and 10b p13 — identical colour, three decks apart. (Measured by histogram at 300 dpi. The neighbouring aside on 09a p13 is #92268F, one unit off in green and blue — the same ink to the eye, but the two pages are not bit-identical.)

Examples: inherit from A, override, extend from B from A, Super is B (10b p10, p13, p14, p17, p18); Drone has-a Battery (09a p12); this is the memory location where 42 is stored (02a p13); Note addition happened first (03b p5); ys is an alias of xs, Aliasing relationship broken! (04b p13); a ‘private’ variable, this is called a ‘getter’ (07c p19); unreachable if line 5 errors (07a p14).

Consistency: the strongest single convention in the course — present in 02a, 03b, 04b, 07a, 07b, 07c, 09a, 10b. Weeks 2 through 10.

Boxed token. A thin rectangle drawn around an identifier inside the listing, marking the thing being named. The box colour is not fixed: purple around Point() and self (07c p9, p16), magenta around raise ZeroDivisionError (07a p18), blue around Child and purple around Parent (09b p9). See Inconsistencies.

Brace grouping. A magenta right-brace } spanning consecutive lines, with a magenta italic label beside it — Attributes beside the two self.x = 0 / self.y = 0 lines (07c p9). Single instance.

Pointer arrow. A straight or gently curved arrow from an annotation to the code element it refers to. Magenta in 07c p12 and p16; orange in 09b p12 and p13; blue and purple in 09b p9.

Colour keying. Where an annotation has a coloured box and a coloured arrow and a coloured word in the caption, all three share one colour: on 09b p9 the blue box round Child, the blue arrow, and the word “Child” in the caption are all blue, and Parent is purple throughout. Two instances (09b p9, p12); treat as a good practice rather than a settled rule.

Focus markers. Small green right-pointing triangles in the far-left margin flag the lines the reader should look at (07b p7, p12). Two instances, one deck.

Scope boxes

The clearest original notation in the course, in 07b.

A rounded rectangle drawn over a span of code lines delimits a scope, and its colour names the scope kind:

  • Purple outline, no fill — global scope; encloses the whole snippet (07b p7, p12).
  • Blue outline, pale blue fill — local/function scope; encloses the def body only (07b p7, p9, p12).

Nesting is literal: on 07b p7 and p12 the blue local box sits inside the purple global box.

Each box is paired with a short horizontal arrow leading out to a colour-matched label — purple arrow to purple global variable, blue arrow to blue local variable (07b p7, p8, p9, p12).

Consistency: four pages of one deck, entirely self-consistent. Never reused elsewhere in the semester.

UML class diagrams

The formal UML vocabulary is taught in 10a and reused once in 10b p19.

Class box. A black-outlined rectangle in three compartments, separated by full-width horizontal rules: name (centred, serif) / attributes / methods (both left-aligned). 10a p6 states the rule in words and shows it twice.

Visibility prefixes. Stated explicitly on 10a p6: - private, + public, # protected. Applied consistently on 10a p7–p11: #name: str, -breed: str, +speak().

Attribute typing. name: type with a Python type — #age: int, -nationality: str, -pets: [] (10a p6, p9, p11). Methods show a return type only sometimes: +info(): str (10a p6) but bare +info() (10a p7–p11).

Empty compartments are kept. Cat on 10a p8–p11 keeps a visibly empty attributes compartment rather than collapsing to two compartments.

Single-compartment boxes are acceptable when only structure is being shown — 10a p4 and 10b p19 draw name-only boxes.

Relationship symbols

Relationship Symbol Evidence
Inheritance Solid line, solid filled triangular arrowhead, pointing up into the parent 10a p4, p7–p11; 10b p19
Association Plain solid line, no head, optional verb label at one end 10a p8 (drinks), p9 (Associated)
Composition Solid line, filled diamond at the “whole” end 10a p10
Aggregation Solid line, hollow (white-filled) diamond at the “whole” end 10a p11
WarningThe inheritance arrowhead is filled, not hollow

Standard UML draws generalisation as a hollow triangle. This course draws it solid filled, verified at 600 dpi on 10a p7 and again on 10b p19. Every inheritance arrow in the course is filled. If you conform to standard UML you will not match the slides; if you match the slides you will not match standard UML. Follow the course.

Line routing is orthogonal. All relationship lines use right-angle elbows, never diagonals (10a p8–p11). A parent with several children gets a single vertical stem down from the parent to a horizontal bus, with vertical drops to each child (10a p4, p7–p11; 10b p19).

Layout and flow. Parent above, children in a row beneath. A grandchild hangs directly below its own parent with its own vertical arrow (10b p19: C below B). Associated non-hierarchy classes sit to the side at the same height as the class they attach to (10a p9 Vet, p10 Heart, p11 Owner).

Multiplicity. Placed above the line, adjacent to the end it qualifies, in magenta — 1..* at both ends (10a p9), 1 and 1 (10a p10), 0..* (10a p11). 10a p9 gives the vocabulary in a legend box: 0..1 zero to one, n specific number, 0..* zero to many, 1..* one to many, m..n specific range.

Magenta marks the relationship being taught. On each of 10a p7–p11 the relationship introduced on that slide is drawn in magenta while previously-established structure reverts to black. On p7 the inheritance tree is magenta; by p8 it is black and the new association line is magenta. Consistency: holds on all five relationship slides — a deliberate, reusable device.

Legend box. A rounded rectangle with a purple #7030A0 outline, containing the relationship name in purple and the bare symbol drawn beneath it, parked in the top-left corner (10a p7 Inheritance, p8 Association, p10 Composition, p11 Aggregation). The multiplicity legend on 10a p9 uses the same box for a text list instead of a symbol.

Non-UML class and object diagrams

Before UML is taught in week 10, the course draws classes at least four other ways. These are not variants of one style — they are four unrelated idioms.

(a) Uniform blue hierarchy — flat steel-blue #4F81BD filled rectangles, white sans-serif labels, parent above and children in a row, joined by a #3D6696 orthogonal bracket with no arrowhead at all — a darker shade of the box fill, not black, though it reads as black at slide size. Photos of instances sit below each child. (09b p2, p3)

(b) Multi-colour hierarchy — parent box black with white text; each child a different Office-palette fill — and these are the stock Office 2007 accents exactly, which is why they recur: #C0504D brick red, #4BACC6 teal, #F79646 orange, #215968 dark teal, olive. Connectors are thin #4A7EBB straight lines — diagonal from the outer children, vertical from the one directly beneath — and each ends in its own arrowhead. On 09b p5 three arrowheads overlap on Animal’s bottom edge; at slide size they read as one, but there are three. (09b p4, p5, p6)

Black for the root holds in all three of these diagrams (Employee, Animal, Person). The child colours carry no meaning I can find — Dog stays teal on 09b p5 even though it is itself a parent.

(c) Attributes-over-methods box — the class name in purple bold sans-serif above two stacked magenta-outlined boxes: attributes on top, methods beneath, with a photo of an instance alongside. (07c p6, three times: Dog, Student, Smartphone)

(d) Attributes-left / methods-right — the class in a black-outlined box in the centre with its name in black and (class) beneath in magenta; a purple-outlined attributes box to the left and a magenta-outlined methods box to the right, each with a plain black label above it. Instances are photographs below, reached by straight black downward arrows with solid heads. (08a p2)

NoteInstantiation arrows point down; inheritance arrows point up

08a p2 draws class → instance as a downward arrow. Every inheritance arrow in the course points up to the parent. The two are never shown on the same page, so the contrast is safe — but keep it.

(e) Containment (“has-a”) boxes — composition is drawn as nesting, not as a line. A large steel-blue #4080B0 filled rectangle is the whole, labelled in large white text at its right edge (car, drone); a smaller brick-red #C05040 rounded rectangle sits inside it and is the part, labelled in white at its top with its methods listed beneath (engine / stop() / start()). (09a p6, p16)

Substitution is shown by stacking two such figures and joining them with a thick curved orange #F79646 arrow from the old configuration to the new (09a p16, “Hot-Swapping”).

Consistency: (e) holds twice in one deck and is the course’s only purpose-built composition picture. (a)–(d) are one or two pages each.

The large worked example

10a p13 — the only whole-system class diagram in the course — is drawn in a completely different style from the rest of 10a:

  • Single-compartment boxes, name only, pastel fills with matching darker strokes.
  • Sampled fills #D0E0F0 blue / #D0E0D0 green / #F0E0C0 orange, with strokes #6080B0 / #80B060 / #D09000. These are the draw.io / diagrams.net default shape colours, matched exactly — this figure was built in draw.io with stock styling, not drawn to match the deck.
  • Dashed lines with small open arrowheads for association/dependency (WTController → WTView, WTModel → Tank), solid lines with the usual filled triangle for inheritance.
  • Tiny 1 / N multiplicities at the line ends.
  • Green fill appears on Tank, Tile and Enemy — the three classes that have subclasses. This is my inference from one figure, and Battlefield (blue, no subclasses) is consistent with it while WTView (orange, alone) is not explained. Do not rely on it.

Reference and memory diagrams

The course does not draw its own reference diagrams. It uses Python Tutor.

pythontutor.com output is embedded as a screenshot in 07b p7, p12 and 07c p13, p14, and named as a live-demo cue five times in 02a (p22, p24, p25, p26, p27, captioned Python Tutor 1. through Python Tutor 5.).

The Python Tutor rendering, as it appears in those screenshots:

  • Two columns under bold headers Frames (left) and Objects (right).
  • A frame is a pale blue box with a bold title (Global frame) and one row per name; each row is name right-aligned against a value cell.
  • An object is a pale yellow box with a small red-brown type caption floating above it — Point class, Point instance, function.
  • An attribute inside an instance is a two-cell row: grey name cell, white value cell.
  • A reference is a curved blue-grey arrow from a frame slot to the object.
  • Aliasing is shown by two arrows converging on one object (07c p14), versus two arrows to two separate objects for equal-but-distinct values (07c p13).

Consistency: two decks, four screenshots, plus five named references in a third deck spanning week 2 to week 7. Treat Python Tutor as this course’s canonical memory picture.

Bit and memory notation

Established in 02a and legended explicitly on p4.

  • A bit is a square cell. Filled black = on/1. White with a black outline = off/0. 02a p4 draws the two side by side and labels them On and Off.
  • Held on 02a p6, p7, p8, p9, p10, p11, p12 — seven further pages.
  • A bit string is a horizontal row of contiguous squares, read left to right, with . . . after the last cell for continuation (02a p10, p11).
  • Memory is rows of words stacked vertically, each row prefixed in the left margin by its address as a small decimal number (02a p12: 381–388).
  • Enumerating all n-bit patterns stacks one row per pattern (02a p7, p8, p9).

Consistency: very strong within 02a. Never used again — no later deck draws a bit.

Data-structure and algorithm-trace diagrams

NoteThe one explicit figure-source statement in the course

12b p2: “Note: The diagrams from today’s lecture are taken from runestone.academy.”

This is the closest thing CSSE1001 has to a textbook lineage, and it governs every sorting and merge-tree figure in 12b (p4, p7, p10, p13, p14). Those figures are Runestone Academy’s, not the lecturer’s, which is why their visual language matches nothing else in the course.

List cells. A list is a horizontal row of adjacent square cells with a thin grey border and a soft drop shadow, one integer per cell in small sans-serif, centred. (12b p4, p7, p10, p13, p14)

Shading marks state. White = untouched; grey fills mark the cells the current step is acting on or the region already sorted. The exact meaning of each grey level is never legended — see Not established.

A trace runs top to bottom. Each row is one step; time advances downward. (12b p4, p7, p10)

Step captions sit to the right of each row, small black sans-serif, in the present tense of what just happened: 93 is largest, inserted 26, Exchange / No Exchange, 91 in place after first pass. (12b p4, p7, p10)

Movement arrows are thin black orthogonal arrows drawn above the row, running from source cell to destination cell (12b p4). A whole pass gets a long labelled arrow spanning the figure above everything else — First pass (12b p10).

Recursion trees (merge sort, 12b p13–p14) are drawn as binary trees of list-rows:

  • Merge Sort – Winding (p13): the full list at the top, splitting downward, arrows pointing down from a list to its two halves.
  • Merge Sort – Unwinding (p14): the singletons at the top, arrows pointing down into each merged result, ending in the sorted list at the bottom.

Both use downward arrows. The recursion direction is carried by the slide title and by which end of the tree holds the whole list — not by arrow direction. This is easy to get wrong.

Mathematical and logical notation

Truth tables (03b p6, p7). A 3×3 grid with visible black rules; the operator name sits in the top-left cell in cyan monospace (and, or); the header row and header column carry the operand values in black monospace; a double rule separates the headers from the body. The one semantically interesting result is coloured magenta — the single True for and (p6), the single False for or (p7).

Function signatures are given above the table, centred, mixing monospace names with maths: and : 𝔹 × 𝔹 → 𝔹. Also > : ℤ × ℤ → 𝔹 (03b p5) and P : ℕ → {True, False} (12a p11).

Blackboard bold for domains — 𝔹 booleans (03b p4, p5, p6, p7), ℤ integers (03b p5), ℕ naturals (12a p11, p13). 𝔹 = {True, False} is defined with the Python literals inside the set, in monospace (03b p4).

Python literals stay in monospace inside maths. True and False are never italicised into maths variables.

Implication and quantifiers use ⟹ and ∀: (P(0) and (P(n) ⟹ P(succ(n)))) ⟹ ∀m ∈ ℕ, P(m) (12a p11). Note and stays as the Python keyword in monospace even inside a mathematical statement.

Contradiction is ⇒⇐ (02a p20).

Displayed maths is centred on its own line, in magenta when it is the point being made (02a p20, 12a p11).

Arrow chains stand in for flow diagrams. Simple pipelines are written inline as text with → rather than drawn: state change → _check_invariants → valid (08b p8), parent → child → grandchild (10b p12), Task + TodoList → Model (domain) (11a p8). Consistency: three decks. This is why the course has so few real flow diagrams.

Geometric and proof figures

The chessboard-tiling figures for the induction proof (12a p12, p14, p15):

  • The construction is drawn in cyan solid lines.
  • The underlying reference grid is grey dashed.
  • The distinguished (uncovered) square is a filled magenta disc.
  • Dimensions are annotated with cyan extension lines outside the figure, labelled in black serif maths (2ⁿ, 2ⁿ⁺¹), placed below and to the right.

Consistency: three pages, one deck, entirely self-consistent.

The one flow diagram

07a p17 is the only control-flow diagram in the 726 pages. It shows try/except/else/finally:

  • Nodes are rounded rectangles with a hand-drawn, wobbly grey stroke (a sketch/xkcd style).
  • The node label is the bare Python keyword in monospace, coloured per keyword: try teal, except magenta, else blue, finally purple.
  • finally is drawn with a dashed sketchy border; the other three are solid.
  • Flow runs top to bottom, with curved grey arrows looping out to the left.
  • Edge captions are bold sans-serif, placed below the arrow they describe: Run the code under try, Execute the code under except when there is an exception, No exceptions? run the code under else after try, Always run this code.
  • Status glyphs sit outside the flow: a purple circled ✗ beside the try→except path, a green circled ✓ beside the try→else path, a blue circled i beside finally.
Warning

This is a single instance. It does not establish a general flowchart convention for the course — see Not established.

The LEGB diagram

07b p13 draws name resolution as a vertical cascade:

  • Four levels listed top to bottom, each with its initial letter bold — Local, Enclosing, Global, Built-in.
  • Between consecutive levels, a large red hook arrow with the small red caption If not found to its left.
  • The cascade terminates in bold red Error!.

Red marks the failure path. Single instance.

Naming and capitalisation

The three rules the course states in words, not just in examples:

Kind Rule Evidence
Variables, functions lowercase, words separated by underscores — descriptive_variable_name 03a p25
Classes CamelCaps — “That is ClassNamesAreLikeThis” 07c p7
Constants SNAKE_CASE_CAPS 07b p5

03a p24 states the course follows Google’s PEP, “a variant of PEP8”, with both linked as lavender rounded chips. 03a p26: lines must be strictly less than 80 characters.

These rules govern labels in diagrams too. UML boxes use CamelCaps class names (DeliveryRobot, WTController, DroneFlight) and snake_case members (_check_invariants(), has_solar_panels, battery_level) throughout 10a, 10b, 07c and 08a.

Do/don’t pairs. Compared alternatives go in a two-column table headed Yes and No in magenta italic, with a single rule under the headers and no other lines — good on the left, bad on the right (03a p25, p28). The variant form labels two separate ruled listings Not helpful / Helpful in magenta italic (03a p27). Inside dark-theme code screenshots the same judgement is made with an all-caps comment — # BAD! / # GOOD! (08b p7).

Figure sourcing and attribution

No textbook is cited as a figure source anywhere. A full-text search of all 25 decks and the course profile for textbook, figure-source and adaptation language returns only the four items below. The course profile prescribes no textbook at all.

Attribution Where Scope
Based on slides from Dr. Azadeh Ghari-Neiat Title page of 07a, 07b, 07c, 08a, 08b, 09a, 09b, 10a, 10b, 11a Slide lineage, not figure lineage
Based on slides from Dr. Azadeh Ghari-Neiat and Dr. Paul Vrbik 07b title page as above
Note: The diagrams from today's lecture are taken from runestone.academy. 12b p2 All sorting figures in 12b
Image source: www.freepik.com 09a p9 That slide’s stock art
Images are from WIRED 09b p2, p3 Those slides’ photos
Inspired by the example of MIT6.100L slide. 07c p10 The blueprint/house analogy — an idea, not a figure family

Placement. Credits are set in tiny centred or bottom-right roman type beneath the figure (09a p9, 07c p10) or in the bottom-right corner of the slide (09b p2, p3).

10b p9 refers to “the course notes” as the source of a code snippet — the course has its own written notes (delivered via Ed Lessons) which are not among these materials and may carry conventions this note cannot see.

Page furniture

  • Slide titles: dark blue #3030B0, serif, upper-left, sentence case with title-case content words. Optional Content: is used as a prefix for non-examinable material (10b p5).
  • Footer: n / N in tiny grey at the bottom-right. Unreliable — see How to read the citations.
  • Title slide: course code and title in blue, lecture number and name in magenta italic, lecturer, date, then the attribution line. (10a p1, 09a p1, 09b p1, 10b p1, 11a p1)
  • QR-code slides: a large centred QR code with the URL in small serif beneath, flanked by decorative 3D clip art, no title (07a p19, 07b p18, 09b p19).

Inconsistencies

Places where the course does the same thing more than one way. Both readings are recorded; a decision is needed before drawing.

1. Two entirely different UML idioms inside one deck

10a p4–p11 draws three-compartment black-outlined class boxes with magenta relationship lines, orthogonal routing and no fills. 10a p13 draws single-compartment pastel-filled draw.io boxes with dashed dependency arrows. Same deck, same lecture, same subject. 10b p19 adds a third variant: single-compartment boxes with navy #103040 outlines. Decide: compartments or not, fills or not, box outline colour.

2. Class boxes are drawn four incompatible ways before week 10

Three-compartment black box (10a p6); attributes-box-above-methods-box with the name outside and magenta outlines (07c p6); attributes-left/methods-right around a central black name box (08a p2); plain filled rectangle with name only (09b p2, p4). Decide which is canonical for pre-UML material.

3. Inheritance connectors: three styles

Orthogonal bracket with no arrowhead (09b p2, p3); straight blue lines each with its own arrowhead, overlapping at the parent (09b p4, p5, p6); orthogonal bracket with a filled triangular arrowhead (10a p4, p7–p11; 10b p19). Decide.

4. Hierarchy box colour: uniform vs. per-child

09b p2/p3 fill every box the same steel blue. 09b p4/p5/p6 make the root black and give each child its own colour. The two appear two pages apart. And 10a p13 uses a third scheme where colour may track “has subclasses”. Decide whether fill colour means anything at all.

5. Warning heading: red or purple

Red #F00000 in 12a p10 and 04b p14. Purple #7030A0 in 07b p6. Decide.

6. Two greens for the same role

Question / Exercise / Example / Task are #109050 in the LaTeX decks (02a p5, 03b p11) but #00B050 in the PowerPoint ones (10a p12, 11a p8). Same meaning, two hexes. Additionally 01a p25 sets Question in a magenta/crimson rather than either green (observed visually; my colour sample of that page missed the heading). Decide one green.

7. Boxed-token highlight colour is unfixed

Purple (07c p9, p16), magenta (07a p18), blue-and-purple keyed to two referents (09b p9). Decide.

8. Three code presentations

Ruled + line-numbered LaTeX listings (most decks); dark-theme screenshots of an IDE (09b p8–p13, p16; 10b p2, p4, p5; 08b p7); and plain unruled, unnumbered monospace (07a p16, p20). 09b switches between the first two within a single deck. Decide.

9. Summary styling

Purple block heading (02a p28, 07a p21, 07b p19); blue slide title (10a p14, 11a p14); magenta (09b p18). Decide.

10. Image credits are given inconsistently

09a p9 and 09b p2/p3 credit their stock photography. 01a p23–p29 (Ada Lovelace, Grace Hopper, the Jacquard loom, punch cards, the first computer bug), 07c p6/p10, 08a p2/p4 and 12a p4–p9 (the meme sequence) credit nothing. Decide a credit policy.

11. Bit-string reading order

02a p7–p9 enumerate n-bit patterns by toggling the leftmost cell fastest (off-off, on-off, off-on, on-on), which reads the leftmost cell as least significant. 02a p11 then interprets a word as 1·2³² + 1·2³¹ + … + 1·2⁰, reading the leftmost cell as most significant. If you draw a numbered bit string, decide which end is the high bit.

12. Exercise as heading vs. divider

A green block heading in 03b p11, 12b p5, 09b p17, 10a p12, 11a p8 — but a full magenta italic divider slide in 08b p11. Decide.

Not established by the source

Conventions a diagram in this course will plausibly need, that the materials simply do not settle. This is where the risk of invention lies.

No general flowchart convention. The only flow diagram in 726 pages is 07a p17’s sketch-style try/except figure. There is no established shape vocabulary (no decision diamond, no terminator, no process box), no arrow style, and no rule for labelling branches. If you need a flowchart, you are inventing one. Note that the course’s habit is to write flow as an inline → chain (08b p8, 10b p12, 11a p8) rather than draw it — consider doing that instead.

No MVC diagram. The entire MVC deck (11a, 14 pages) contains no architecture diagram. The Model/View/Controller relationship is given as a six-item numbered list (11a p6, p13) and a four-column table (11a p5). The only place the three appear as boxes is 10a p13, where they are three unremarkable draw.io rectangles among thirteen. There is no established shape, layout, arrow direction, or colour for an MVC diagram in this course.

No hand-drawn reference or memory diagram. The course never draws its own variable/object box-and-arrow picture — it screenshots Python Tutor (07b p7/p12, 07c p13/p14). If you need a reference diagram that Python Tutor cannot produce, there is no house style to follow.

No list or aliasing diagram. 04b (non-primitive data, 45 pages) teaches aliasing, copying and pass-by-reference entirely through REPL transcripts — mutating ys and observing xs change (p10, p12, p13). Not one box-and-arrow picture of a list. The idea of “two names, one list” is never drawn outside Python Tutor.

Grey-level semantics in the sorting traces are never legended. 12b p4, p7, p10 use at least three shades — white, light grey, darker grey — and no slide says which is “being compared”, which is “sorted”, and which is “just moved”. Since these figures are Runestone’s, the course has no stated rule to appeal to.

No stated meaning for fill colour in class boxes. 09b p5’s brick red, teal and orange appear decorative; 10a p13’s green may mark classes with subclasses but this is one figure and WTView’s orange contradicts any simple reading. There is no colour key anywhere.

No convention for showing a method body, call stack, or sequence of calls. Despite 12a (recursion, 47 pages) there is no call-tree or stack-frame diagram of the course’s own making — recursion is taught with memes (p4–p9), induction on chessboards (p12–p15) and code. No UML sequence diagram, activity diagram, state diagram or object diagram appears anywhere in the course.

No rule for typing method returns in UML. 10a p6 writes +info(): str; 10a p7–p11 write +info(). Both are the same method on the same class in the same deck.

No hex values are ever published. Every colour in this note was sampled from the rendered PDFs. The course states no palette, so a redrawn figure matching these hexes matches the slides by measurement, not by declaration.

Abstract classes have no notation. 10b p3–p5 teaches abstract base classes in prose and code only. UML’s italic-name convention for abstract classes is never used; Shape is never drawn.

Line weights, font sizes and box dimensions are never specified, and vary between the two slide families.

The eight unread decks. 00-welcome, 01b, 02b, 04a, 05a, 05b, 06a, 06b were not read as images. They contain no embedded raster images (except 00-welcome’s six photo pages) and are in the LaTeX family, so they are unlikely to hide a new idiom — but this note cannot rule it out.

The written course notes. 10b p9 cites “the course notes” as a source. Those notes are delivered through Ed Lessons and are not part of these materials. If they contain diagrams, they may establish conventions that contradict this note.

See also

Python Dunder (Magic) Methods

Dunder (“double underscore”) or magic methods are special methods, named __like_this__, that Python calls automatically to implement built-in behaviour for a type — instantiation, printing, equality, arithmetic operators, and more. You don’t call them directly; Python invokes them on your behalf when the corresponding syntax/built-in is used.

See 2025-09-16-dunder-methods for the lecture note, and python-classes-and-objects for classes generally.

Common dunder methods

Method Called by Purpose
__init__(self, ...) ClassName(...) Initializes a new instance. Returns None — it fills in an object that already exists rather than producing one.
__str__(self) print(obj), str(obj) User-friendly display string.
__repr__(self) the REPL, repr(obj) Unambiguous, developer-facing string — ideally a valid Python expression that recreates the object via eval().
__eq__(self, other) obj == other Custom equality (instead of identity).
__add__(self, other) obj + other Addition.
__sub__(self, other) obj - other Subtraction.
__neg__(self) -obj Unary negation.
__len__(self) len(obj) Length.

Every binary method takes the left operand as self and the right one as other.

__repr__ vs. __str__

  • __repr__ is for the programmer: unambiguous, meant for debugging/logging, ideally eval(repr(obj)) reconstructs an equal object. The round trip is obj → repr() → source text → eval() → a second object, whose repr matches the first’s.
  • __str__ is for the user: a friendly, readable string, used by print().
  • If only __repr__ is defined, print() falls back to it. If neither is defined, printing an object shows its default <... object at 0x...> representation.

A consequence that catches people out: at the interactive prompt, >>> obj and >>> print(obj) can produce completely different text from the same object, because they go through different methods.

Type-hinting a class inside its own body

Methods like __add__ want to say they return the class being defined, but the class object doesn’t exist yet while the body is executing:

from __future__ import annotations   # makes annotations lazy (strings)

class Fraction():
    def __add__(self, other) -> Fraction:   # legal because of the import
        ...

Without that import, -> Fraction is evaluated immediately and raises NameError; the alternative is to quote it, -> "Fraction".

Overloadable operators

Binary Method Unary Method Comparison Method
+ __add__ - __neg__ < __lt__
- __sub__ abs __abs__ <= __le__
* __mul__ ~ __invert__ == __eq__
** __pow__ != __ne__
// __floordiv__ > __gt__
/ __truediv__ >= __ge__

Operators can be defined in terms of each other rather than from scratch — Fraction.__sub__ is just return self + -other, i.e. __add__ composed with __neg__.

Instance variables vs. class variables

An instance variable (self.x = ...) belongs to one specific object — each instance has its own copy. A class variable (declared directly in the class body) is shared by all instances of the class, and can be accessed either via an instance (obj.class_var) or via the class itself (ClassName.class_var), without needing any instance at all.

class Clicker():
    _all_clicks = 0   # class variable -- shared by every instance

    def __init__(self) -> None:
        self._clicks = 0   # instance variable -- unique per object

    def click(self) -> None:
        self._clicks += 1
        Clicker._all_clicks += 1

Why Clicker._all_clicks += 1 and not self._all_clicks += 1. self._all_clicks += 1 expands to self._all_clicks = self._all_clicks + 1. The read on the right-hand side finds the class attribute (attribute lookup falls back to the class when the instance has no such name), but the assignment on the left always writes an instance attribute. So the first click on each object creates a private _all_clicks on that object that shadows the shared one forever, and the class-level total stays at 0. Naming the class explicitly is what makes the update land on the shared cell.

Reading through an instance is fine — c._all_clicks returns the class’s value, which is why the transcript in 2025-09-16-dunder-methods shows (6, 6, 6). It is only assignment through an instance that breaks the sharing.

Worked example: Vector2D

A fuller worked example combining several dunder methods together. The length is Euclidean: for (2, 3) it is sqrt(13), 3.605551275463989.

import math

class Vector2D():
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def length(self):
        return math.sqrt(self.x**2 + self.y**2)

    def __repr__(self):
        return f"Vector2D(x={self.x}, y={self.y})"

    def __str__(self):
        return f"2D Vector: ({self.x}, {self.y}) --- length: {self.length()}"

    def __eq__(self, other):
        return isinstance(other, Vector2D) and self.x == other.x and self.y == other.y

    def __add__(self, other):
        if not isinstance(other, Vector2D):
            return NotImplemented
        return Vector2D(self.x + other.x, self.y + other.y)

    def __len__(self):
        return 2
>>> u = Vector2D(2, 3)
>>> v = Vector2D(4, 5)
>>> print(u + v)
2D Vector: (6, 8) --- length: 10.0
>>> print(u)          # calls __str__
2D Vector: (2, 3) --- length: 3.605551275463989
>>> repr(u)            # calls __repr__
'Vector2D(x=2, y=3)'
>>> u == v              # calls __eq__
False
>>> len(u)               # calls __len__
2

print(u + v) uses two magic methods in one expression: __add__ builds the new vector, then print displays it through __str__.

Returning NotImplemented (rather than raising or returning False) from a method like __add__ is the standard way to signal “I don’t know how to combine these two types” — it lets Python fall back to the other object’s reflected method, or raise a clean TypeError if nothing handles it.

Python Representation Invariants

A representation invariant is a condition or property that must remain true about an object’s internal state throughout its lifetime. They’re primarily a development-time tool: they help catch bugs early, simplify method implementations (since you can assume a valid starting state), and document the assumptions a class relies on.

See 2025-09-16-representation-invariants for the lecture note.

Documenting invariants

State invariants in the class docstring, underneath its attributes:

class Fraction():
    """Represents a mathematical fraction.

    Representation Invariants:
    - denominator != 0
    - if fraction is zero, it is represented as 0/1
    - if fraction is negative, numerator is negative
    """

A good invariant is a checkable statement about the stored attributes — something a method could evaluate and get True or False from. “The denominator is not zero” is an invariant; “this class models fractions” is not.

Establishing vs. checking

There are two ways to make an invariant hold, and they are easy to confuse:

  • Establish it — normalise the input so the property is true by construction, e.g. if denom < 0: numer, denom = -numer, -denom.
  • Check it — assert the property and fail if the caller got it wrong, e.g. assert denom > 0.

Fraction uses both, on different invariants. Centralising all the checks in _check_invariants() pushes you toward the second style: the method can only report, not repair, so anything you want normalised has to be normalised before it is called.

Enforcing invariants

Assertions

assert <condition that should be true>, "message if it's not"
  • Raises AssertionError if the condition is false.
  • Disabled when Python is run with optimization (python -O) — so asserts should catch bugs, not perform real input validation that must always run (use raise ValueError(...) etc. for that).

assert for bugs, raise for callers

The distinction matters enough that DroneFlight uses both in one class:

def _check_invariants(self) -> None:
    assert 0.0 <= self._altitude <= self._MAX_ALT, "Altitude out of range."

def set_altitude(self, value: float) -> None:
    if not isinstance(value, (int, float)):
        raise TypeError("Altitude must be a number.")
    if not 0.0 <= value <= self._MAX_ALT:
        raise ValueError(f"Altitude must be 0-{self._MAX_ALT} m.")
    self._altitude = float(value)
    self._check_invariants()

_check_invariants() asks “is my own code still correct?” — a false answer is a bug, and it is fine for that check to disappear under -O. set_altitude() asks “did the caller hand me something usable?” — a false answer is expected behaviour, and it must keep raising in production. See python-exceptions for the exception types.

The _check_invariants() helper pattern

Centralise all invariant checks in one private method, and call it:

  • At the end of __init__.
  • At the end of any method that mutates state.
  • At the start of any method that relies on the invariants already holding.
def _check_invariants(self) -> None:
    assert self._denom != 0, "Denominator cannot be zero."
    ...

Two habits that keep the number of call sites small:

  • Route every mutation through one setter. If ascend() and land() both call set_altitude() instead of assigning self._altitude directly, the range check lives in exactly one place.
  • Put the limits in class constants. _ID_LEN = 6 and _MAX_ALT = 120.0 on the class body give the rule one home, so the assertion and the error message change together when the limit does. Only the code that actually reads the constant is protected, though: DroneFlight still hard-codes 0 ≤ _altitude ≤ 120 in its docstring, and interpolating the constant into the message turns it into 0-120.0 m, so the wording drifts from the docstring anyway. See 2025-09-16-representation-invariants for that mismatch.

Encapsulation: don’t expose mutable internals

Returning a direct reference to a private mutable attribute (like a list or dict) lets external code silently violate the class’s invariants:

def get_members(self):        # BAD -- exposes the real list
    return self._members

def get_members(self):        # GOOD -- caller gets an independent copy
    return list(self._members)

This is the aliasing behaviour of python-lists showing up inside a class: the getter hands out a second name for the same list object, so the caller’s append mutates the object’s state without any of its methods running — and therefore without any assertion getting a chance to fire.

Best practices

  • Document invariants in docstrings.
  • Centralise invariant checking in a single method.
  • Don’t expose methods/attributes that could let external code violate invariants.
  • Write test cases that target edge cases (see python-testing).
  • Type hints can express some invariants, but not all (e.g. numeric ranges still need explicit checks).
  • Balance strictness with practicality — not every property needs an assertion.