2.1.1 · D3OOP Fundamentals

Worked examples — Class vs object — blueprint vs instance

2,179 words10 min readBack to topic

Throughout, we reuse one blueprint. Read it once — every example builds on it.

class Dog:
    species = "Canis"                 # CLASS attribute (one copy, shared)
 
    def __init__(self, name, age):    # constructor: runs once per object
        self.name = name              # INSTANCE attribute (own copy)
        self.age  = age
 
    def bark(self):
        return f"{self.name} says Woof!"

The scenario matrix

Every case this topic can throw at you falls into one cell below. The examples that follow are labelled with the cell they cover.

Cell Scenario The trap it hides
A Two objects, edit one instance attribute Does editing d1 touch d2?
B Change a class attribute for everyone Shared value updates for all
C Shadowing: set instance attr with same name as class attr Instance copy hides the class copy
D Zero objects: touch only the class No instance exists yet — what still works?
E Identity vs equality of two look-alike objects is False, but data equal
F Degenerate: two names pointing at one object Aliasing — one cookie, two labels
G Limiting case: mutable class attribute shared by all Silent cross-object corruption
H Word problem: a real bank-account blueprint Same rules, new costume
I Exam twist: assign to class through an instance Where does the write land?

The figure below is the mental model every example returns to.

Figure — Class vs object — blueprint vs instance

Worked examples


Recall Rebuild the matrix from memory

Edit d1.age, does d2 change? ::: No — instance data is per object (Cell A). Dog.species = X, do all instances see X? ::: Yes — one shared class copy (Cell B). d1.species = X, does the class change? ::: No — it creates a shadow on d1 only (Cell C, I). a = Dog(); b = Dog(); a is b? ::: False — separate memory cells (Cell E). b = a; b.age = 9; a.age? ::: 9 — same object, two labels (Cell F). Shared list class attr, .append on one instance? ::: Every instance sees it — mutation hits the shared object (Cell G).

Connections

  • Constructors and __init__ — where instance attributes are born.
  • self and instance methods — how self targets the current object.
  • Class vs instance attributes — the shared-vs-own split behind every cell.
  • Encapsulation — bundling this state safely.
  • Identity vs Equality (is vs ==) — Cells E and F.
  • Memory model and references — aliasing in Cell F.