{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "adv-0001",
   "metadata": {
    "language": "markdown"
   },
   "source": [
    "# Advanced OOP Topics\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "adv-0002",
   "metadata": {
    "tags": [
     "hide-input",
     "thebe-init"
    ]
   },
   "outputs": [],
   "source": [
    "import sys\n",
    "from pathlib import Path\n",
    "\n",
    "current = Path.cwd()\n",
    "for parent in [current, *current.parents]:\n",
    "    if (parent / '_config.yml').exists():\n",
    "        project_root = parent\n",
    "        break\n",
    "else:\n",
    "    project_root = Path.cwd().parent.parent\n",
    "\n",
    "sys.path.insert(0, str(project_root))\n",
    "\n",
    "from shared import thinkpython, diagram, jupyturtle, download\n",
    "\n",
    "sys.modules['thinkpython'] = thinkpython\n",
    "sys.modules['diagram'] = diagram\n",
    "sys.modules['jupyturtle'] = jupyturtle\n",
    "sys.modules['download'] = download\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "adv-0003",
   "metadata": {
    "language": "markdown"
   },
   "source": [
    "This section covers six topics. Its banking examples reuse the owner/balance `BankAccount` from {doc}`OOP Design and Methods <0901-oop-design>`, not the numbered-account hierarchy from {doc}`The Four Pillars <0902-oop-pillars>`.\n",
    "\n",
    "| Required topic | What it adds |\n",
    "|---|---|\n",
    "| Comparison methods | Value equality and ordering with `__eq__` and `__lt__` |\n",
    "| Operator overloading | A nonmutating `+` operation with a defined result |\n",
    "| `@dataclass` | Generated methods, field order, and independent mutable defaults |\n",
    "| `namedtuple` | Tuple-compatible records with named fields |\n",
    "| Class vs. instance variables | Shared defaults and per-instance shadowing |\n",
    "| Static and class methods | Parsing helpers and alternative constructors |\n",
    "\n",
    "**Optional enrichment:** `total_ordering`, hashability, frozen dataclasses, and the shared mutable class-variable trap are labeled where they appear. The required examples and practice do not depend on them."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "```{contents}\n",
    ":local:\n",
    ":depth: 2\n",
    "```"
   ],
   "id": "contents"
  },
  {
   "cell_type": "markdown",
   "id": "adv-0010",
   "metadata": {
    "language": "markdown"
   },
   "source": [
    "## Comparison Dunder Methods\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-adv-0010",
   "metadata": {},
   "source": [
    "```{index} equality method (__eq__), object identity\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "adv-0011",
   "metadata": {
    "language": "markdown"
   },
   "source": [
    "For a new class that inherits `object`'s equality behavior, two distinct instances compare unequal even if their attributes agree. `is` tests identity. Defining `__eq__` lets `==` express the class's chosen value-equality rule."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "adv-0012",
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": "False\nFalse\n"
    }
   ],
   "source": [
    "class Point:\n",
    "    def __init__(self, x, y):\n",
    "        self.x = x\n",
    "        self.y = y\n",
    "\n",
    "    def __repr__(self):\n",
    "        return f'Point({self.x}, {self.y})'\n",
    "\n",
    "p1 = Point(1, 2)\n",
    "p2 = Point(1, 2)\n",
    "\n",
    "print(p1 == p2)   # False: identity check by default\n",
    "print(p1 is p2)   # False\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "adv-0013",
   "metadata": {
    "language": "markdown"
   },
   "source": [
    "Adding `__eq__` makes `==` compare by value instead.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch09-notimplemented",
   "metadata": {},
   "source": [
    "A binary special method receives the other operand as `other`. Before reading its attributes, decide whether that operand's type is supported. Return the special value **`NotImplemented`** when it is not. This means \"this method does not handle that type,\" not \"the values are unequal.\" It is also different from raising `NotImplementedError`.\n",
    "\n",
    "Python can then try the other operand's comparison method or an operator-specific fallback. For two unsupported equality operands, `==` ultimately falls back to identity. Unsupported ordering or addition normally raises `TypeError` when neither operand handles the operation. Never treat `NotImplemented` itself as a Boolean answer."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-ch09-notimplemented",
   "metadata": {},
   "source": [
    "```{index} NotImplemented, unsupported operand\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "adv-0014",
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": "True\nFalse\nFalse\n"
    }
   ],
   "source": [
    "class Point:\n",
    "    def __init__(self, x, y):\n",
    "        self.x = x\n",
    "        self.y = y\n",
    "\n",
    "    def __repr__(self):\n",
    "        return f'Point({self.x}, {self.y})'\n",
    "\n",
    "    def __eq__(self, other):\n",
    "        if not isinstance(other, Point):\n",
    "            return NotImplemented\n",
    "        return self.x == other.x and self.y == other.y\n",
    "\n",
    "p1 = Point(1, 2)\n",
    "p2 = Point(1, 2)\n",
    "p3 = Point(3, 4)\n",
    "\n",
    "print(p1 == p2)   # now True\n",
    "print(p1 is p2)   # still False\n",
    "print(p1 == p3)   # False\n",
    "\n",
    "# print(p1)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch09-comparison-predict",
   "metadata": {},
   "source": [
    "Predict the difference between asking the method directly and using the equality operator:"
   ]
  },
  {
   "cell_type": "code",
   "id": "ch09-comparison-predict-code",
   "metadata": {},
   "execution_count": 4,
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": "True\nFalse\nOrdering is not supported for this pair\n"
    }
   ],
   "source": [
    "print(p1.__eq__((1, 2)) is NotImplemented)  # True: this method declines the tuple\n",
    "print(p1 == (1, 2))                        # False: Python applies equality fallback\n",
    "try:\n",
    "    print(p1 < (1, 2))\n",
    "except TypeError:\n",
    "    print('Ordering is not supported for this pair')\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch09-comparison-feedback",
   "metadata": {},
   "source": [
    "The direct method call returns a sentinel, while `==` returns a Boolean after dispatch and fallback. The ordering attempt raises because this version of `Point` has no ordering implementation. The next example adds an ordering rule for pairs of points."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "adv-0015",
   "metadata": {
    "language": "markdown"
   },
   "source": [
    "### Ordering with `__lt__`\n",
    "\n",
    "To support `sorted()`, `min()`, and `max()`, define `__lt__(self, other)`. Return a Boolean for supported operands and `NotImplemented` otherwise. Equality and ordering are design decisions: this version compares points by distance from the origin, breaking equal-distance ties by coordinates.\n",
    "\n",
    "The tuple `(distance, x, y)` is the **comparison key**. Python compares its first differing element, so equal-distance points still have a deterministic order consistent with coordinate equality. The core example needs no decorator. Deriving additional comparison operators with `total_ordering` is optional enrichment below."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-adv-0015",
   "metadata": {},
   "source": [
    "```{index} less-than method (__lt__), comparison key\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "adv-0016",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": "[Point(1, 1), Point(0, 2), Point(0, 5), Point(3, 4)]\nPoint(1, 1)\nPoint(3, 4)\nTrue\n"
    }
   ],
   "source": [
    "import math\n",
    "\n",
    "class Point:\n",
    "    def __init__(self, x, y):\n",
    "        self.x = x\n",
    "        self.y = y\n",
    "\n",
    "    def __repr__(self):\n",
    "        return f'Point({self.x}, {self.y})'\n",
    "\n",
    "    def __eq__(self, other):\n",
    "        if not isinstance(other, Point):\n",
    "            return NotImplemented\n",
    "        return (self.x, self.y) == (other.x, other.y)\n",
    "\n",
    "    def __lt__(self, other):\n",
    "        if not isinstance(other, Point):\n",
    "            return NotImplemented\n",
    "        own_key = (math.hypot(self.x, self.y), self.x, self.y)\n",
    "        other_key = (math.hypot(other.x, other.y), other.x, other.y)\n",
    "        return own_key < other_key\n",
    "\n",
    "points = [Point(3, 4), Point(1, 1), Point(0, 2), Point(0, 5)]\n",
    "print(sorted(points))\n",
    "print(min(points))\n",
    "print(max(points))\n",
    "print(Point(0, 5) < Point(3, 4))  # True: same distance, compare x next\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch09-order-interpretation",
   "metadata": {},
   "source": [
    "`Point(0, 5)` and `Point(3, 4)` are both five units from the origin. The first coordinate breaks the tie, so the first point sorts earlier. If you only need a one-off sort, `sorted(points, key=...)` from {doc}`Tuples <../06-collections/0603-tuples>` can supply an ordering without changing the class; implement `__lt__` when that order belongs to the type's interface."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "adv-ex-cmp-q",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Comparison Dunders\n",
    "# Required core.\n",
    "# 1. Define Transaction with account and amount, plus __repr__ using !r for account.\n",
    "# 2. Define __eq__ using both attributes and __lt__ using (amount, account).\n",
    "#    Return NotImplemented for an unsupported operand type.\n",
    "# 3. Create Transaction('A-1', 50), Transaction('A-2', 20), and Transaction('A-1', 50).\n",
    "# 4. Print equality of the first and third, sorted transactions, and the maximum.\n",
    "# No decorator or __hash__ is required. The optional value-object extension is below.\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "### Your code ends here.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "adv-ex-cmp-s",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": "True\n[Transaction('A-2', 20), Transaction('A-1', 50), Transaction('A-1', 50)]\nTransaction('A-1', 50)\n"
    }
   ],
   "source": [
    "### Solution\n",
    "class Transaction:\n",
    "    def __init__(self, account, amount):\n",
    "        self.account = account\n",
    "        self.amount = amount\n",
    "\n",
    "    def __repr__(self):\n",
    "        return f'Transaction({self.account!r}, {self.amount})'\n",
    "\n",
    "    def __eq__(self, other):\n",
    "        if not isinstance(other, Transaction):\n",
    "            return NotImplemented\n",
    "        return (self.account, self.amount) == (other.account, other.amount)\n",
    "\n",
    "    def __lt__(self, other):\n",
    "        if not isinstance(other, Transaction):\n",
    "            return NotImplemented\n",
    "        return (self.amount, self.account) < (other.amount, other.account)\n",
    "\n",
    "t1 = Transaction('A-1', 50)\n",
    "t2 = Transaction('A-2', 20)\n",
    "t3 = Transaction('A-1', 50)\n",
    "print(t1 == t3)\n",
    "print(sorted([t1, t2, t3]))\n",
    "print(max([t1, t2, t3]))\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "05ac5f6b",
   "metadata": {},
   "source": [
    "## Operator Overloading\n",
    "\n",
    "By defining special methods, you can control how Python operators\n",
    "behave on your own types. Most operators, and some built-in functions\n",
    "such as `len()`, have a corresponding dunder method:\n",
    "\n",
    "| Operator | Method | Example |\n",
    "|----------|--------|---------|\n",
    "| `+` | `__add__` | `a + b` |\n",
    "| `==` | `__eq__` | `a == b` |\n",
    "| `<` | `__lt__` | `a < b` |\n",
    "| `len()` | `__len__` | `len(a)` |\n",
    "\n",
    "This section focuses on `+` and `len()`; the comparison methods\n",
    "`__eq__` and `__lt__` are covered above.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-05ac5f6b",
   "metadata": {},
   "source": [
    "```{index} operator overloading, addition method (__add__)\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "95f870e8",
   "metadata": {},
   "source": [
    "Here is `__add__` defined on `BankAccount`.\n",
    "When two accounts are added together, a new merged account is returned:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "d5a6f5e0",
   "metadata": {},
   "outputs": [],
   "source": [
    "class BankAccount:\n",
    "    \"\"\"A teaching account with controlled balance updates.\"\"\"\n",
    "\n",
    "    def __init__(self, owner=\"Unknown\", balance=0.0):\n",
    "        if balance < 0:\n",
    "            raise ValueError('Starting balance cannot be negative')\n",
    "        self.owner = owner\n",
    "        self._balance = balance\n",
    "\n",
    "    @property\n",
    "    def balance(self):\n",
    "        \"\"\"Current balance, read-only through the public interface.\"\"\"\n",
    "        return self._balance\n",
    "\n",
    "    def deposit(self, amount):\n",
    "        if amount <= 0:\n",
    "            raise ValueError('Deposit must be positive')\n",
    "        self._balance += amount\n",
    "        return self\n",
    "\n",
    "    def withdraw(self, amount):\n",
    "        if amount <= 0:\n",
    "            raise ValueError('Withdrawal must be positive')\n",
    "        if amount > self._balance:\n",
    "            raise ValueError('Insufficient funds')\n",
    "        self._balance -= amount\n",
    "        return self\n",
    "\n",
    "    def __str__(self):\n",
    "        return f\"BankAccount(owner={self.owner}, balance=${self._balance:.2f})\"\n",
    "\n",
    "    def __repr__(self):\n",
    "        return f\"BankAccount({self.owner!r}, {self._balance!r})\"\n",
    "\n",
    "    def __add__(self, other):\n",
    "        \"\"\"Return a new merged account; leave both operands unchanged.\"\"\"\n",
    "        if not isinstance(other, BankAccount):\n",
    "            return NotImplemented\n",
    "        return BankAccount(f'{self.owner}&{other.owner}', self.balance + other.balance)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "320441b2",
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": "BankAccount(owner=Ava&Ben, balance=$20.00)\n"
    }
   ],
   "source": [
    "a = BankAccount(\"Ava\", 12.00)\n",
    "b = BankAccount(\"Ben\", 8.00)\n",
    "print(a + b)   # BankAccount(owner=Ava&Ben, balance=$20.00)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch09-operator-results",
   "metadata": {},
   "source": [
    "The operation returns a new object; neither account is mutated. The result's owner and balance follow the merge policy stated by this example. Compare that with `deposit()`, which changes one existing object and returns it. Predict the final balances and the unsupported-operand outcome:"
   ]
  },
  {
   "cell_type": "code",
   "id": "ch09-operator-results-code",
   "metadata": {},
   "execution_count": 10,
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": "12.0 8.0 20.0\nFalse False\nCannot merge an account with an integer\n"
    }
   ],
   "source": [
    "merged = a + b\n",
    "print(a.balance, b.balance, merged.balance)  # 12.0 8.0 20.0\n",
    "print(merged is a, merged is b)             # False False\n",
    "try:\n",
    "    print(a + 3)\n",
    "except TypeError:\n",
    "    print('Cannot merge an account with an integer')\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "454003f4",
   "metadata": {},
   "source": [
    "When Python evaluates `a + b`, it calls `a.__add__(b)` automatically.\n",
    "Changing the behavior of an operator so that it works with programmer-defined\n",
    "types is called **operator overloading**.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch09-len-md",
   "metadata": {},
   "source": [
    "Built-in functions use special methods too. `len(obj)` calls `obj.__len__()`, which must return a nonnegative integer. A statement that holds a list of amounts can report how many it has:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ch09-len-code",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "3\n"
     ]
    }
   ],
   "source": [
    "class Statement:\n",
    "    def __init__(self, owner, amounts):\n",
    "        self.owner = owner\n",
    "        self.amounts = amounts\n",
    "\n",
    "    def __len__(self):\n",
    "        return len(self.amounts)\n",
    "\n",
    "statement = Statement('Ava', [100, -20, 35])\n",
    "print(len(statement))   # 3"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "adv-ex-op-q",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Operator Overloading\n",
    "#   1. Define a class Ledger whose __init__(self, owner, entries) stores\n",
    "#      the owner and a list of amounts.\n",
    "#   2. Define __add__ so that ledger1 + ledger2 returns a new Ledger whose\n",
    "#      owner is 'owner1&owner2' and whose entries combine both lists.\n",
    "#      Return NotImplemented if the other object is not a Ledger.\n",
    "#   3. Define __len__ to return the number of entries.\n",
    "#   4. Create Ledger('Ava', [100, -20]) and Ledger('Ben', [50]), add them,\n",
    "#      and print the combined owner, entries, and len().\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "### Your code ends here."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "adv-ex-op-s",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": "Ava&Ben\n[100, -20, 50]\n3\n"
    }
   ],
   "source": [
    "### Solution\n",
    "class Ledger:\n",
    "    def __init__(self, owner, entries):\n",
    "        self.owner = owner\n",
    "        self.entries = entries\n",
    "\n",
    "    def __add__(self, other):\n",
    "        if not isinstance(other, Ledger):\n",
    "            return NotImplemented\n",
    "        return Ledger(f'{self.owner}&{other.owner}', self.entries + other.entries)\n",
    "\n",
    "    def __len__(self):\n",
    "        return len(self.entries)\n",
    "\n",
    "a = Ledger('Ava', [100, -20])\n",
    "b = Ledger('Ben', [50])\n",
    "combined = a + b\n",
    "\n",
    "print(combined.owner)\n",
    "print(combined.entries)\n",
    "print(len(combined))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "adv-0020",
   "metadata": {
    "language": "markdown"
   },
   "source": [
    "## `@dataclass` \n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-adv-0020",
   "metadata": {},
   "source": [
    "```{index} dataclass, dataclass decorator (@dataclass)\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "adv-0021",
   "metadata": {
    "language": "markdown"
   },
   "source": [
    "`@dataclass` is a decorator from the standard library that auto-generates common dunder methods (`__init__`, `__repr__`, `__eq__`) for a class based on its annotated fields, eliminating boilerplate.\n",
    "\n",
    "Dataclasses give type annotations a second job. In a regular class, `name: str` is mostly a hint for readers and tools. In a dataclass, an annotated class variable also becomes a **field** that `@dataclass` uses to generate `__init__`, `__repr__`, and comparison behavior.\n",
    "\n",
    "The table lists its most useful options.\n",
    "\n",
    "| Option | Effect |\n",
    "|---|---|\n",
    "| `eq=True` (default) | Auto-generates `__eq__` based on fields |\n",
    "| `order=True` | Also generates `__lt__`, `__le__`, `__gt__`, `__ge__` |\n",
    "| `frozen=True` (optional below) | Rejects normal field reassignment; hashing still requires hashable field values |\n",
    "| `field(default_factory=...)` | Safe default for mutable fields like lists |\n",
    "\n",
    "When `order=True` is set, fields are compared **in declaration order** (here `name` first, then `gpa`), so `sorted([s1, s2])` places Alice before Bob because `'Alice' < 'Bob'` alphabetically."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "adv-0022",
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": "True\n[Student(name='Alice', gpa=3.8, courses=[]), Student(name='Bob', gpa=3.5, courses=[])]\nStudent(name='Alice', gpa=3.8, courses=['CS101'])\n"
    }
   ],
   "source": [
    "from dataclasses import dataclass, field\n",
    "\n",
    "@dataclass(order=True)\n",
    "class Student:\n",
    "    name: str\n",
    "    gpa: float\n",
    "    courses: list[str] = field(default_factory=list)   # safe mutable default\n",
    "\n",
    "s1 = Student('Alice', 3.8)\n",
    "s2 = Student('Bob', 3.5)\n",
    "s3 = Student('Alice', 3.8)\n",
    "\n",
    "print(s1 == s3)          # True: same field values\n",
    "print(sorted([s1, s2]))  # sorted lexicographically by (name, gpa)\n",
    "s1.courses.append('CS101')\n",
    "print(s1)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch09-dataclass-variation",
   "metadata": {},
   "source": [
    "Field order controls comparisons; it does not mean GPA is the primary key. Predict which Alice comes first, then inspect each instance's `courses` list. `default_factory=list` calls `list()` separately for each instance; it does not share one default list. Type annotations document expected types but do not themselves validate constructor inputs."
   ]
  },
  {
   "cell_type": "code",
   "id": "ch09-dataclass-variation-code",
   "metadata": {},
   "execution_count": 14,
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": "[('Alice', 3.5), ('Alice', 3.8), ('Bob', 3.5)]\n['CS101']\n[]\nFalse\n"
    }
   ],
   "source": [
    "s4 = Student('Alice', 3.5)\n",
    "print([(student.name, student.gpa) for student in sorted([s2, s1, s4])])\n",
    "print(s1.courses)  # ['CS101']\n",
    "print(s3.courses)  # [], unchanged when s1.courses was updated\n",
    "print(s1.courses is s3.courses)  # False\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "adv-0022-default-md",
   "metadata": {},
   "source": [
    "A field can also have a plain default value. Write the value after the annotation, as in `category: str = 'general'`, and callers may then leave that argument out. Fields with defaults must come after the fields without defaults. Plain defaults are for immutable values such as strings, numbers, and `None`. A mutable default such as a list still needs `field(default_factory=list)`, so that each instance gets its own new list; `@dataclass` rejects `notes: list = []` with a `ValueError`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "adv-0022-default-code",
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": "Task(title='Write report', category='general', priority=1)\nTask(title='Fix bug', category='code', priority=3)\n"
    }
   ],
   "source": [
    "from dataclasses import dataclass\n",
    "\n",
    "@dataclass\n",
    "class Task:\n",
    "    title: str\n",
    "    category: str = 'general'   # plain default for an immutable value\n",
    "    priority: int = 1\n",
    "\n",
    "print(Task('Write report'))              # both defaults used\n",
    "print(Task('Fix bug', 'code', 3))        # defaults overridden"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "adv-ex-dc-q",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Dataclasses\n",
    "# Required core.\n",
    "# 1. Define @dataclass(order=True) Expense with amount: float, category: str,\n",
    "#    and notes: list[str] using field(default_factory=list).\n",
    "# 2. Print three expenses sorted by amount, then category for equal amounts.\n",
    "# 3. Append a note to one expense; print another expense's notes to confirm independence.\n",
    "# The frozen Currency variation follows as optional enrichment.\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "### Your code ends here.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "adv-ex-dc-s",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": "[Expense(amount=12.0, category='transit', notes=[]), Expense(amount=42.5, category='groceries', notes=[]), Expense(amount=99.99, category='utilities', notes=[])]\nExpense(amount=42.5, category='groceries', notes=['weekly shop'])\n[]\n"
    }
   ],
   "source": [
    "### Solution\n",
    "from dataclasses import dataclass, field\n",
    "\n",
    "@dataclass(order=True)\n",
    "class Expense:\n",
    "    amount: float\n",
    "    category: str\n",
    "    notes: list[str] = field(default_factory=list)\n",
    "\n",
    "e1 = Expense(42.50, 'groceries')\n",
    "e2 = Expense(12.00, 'transit')\n",
    "e3 = Expense(99.99, 'utilities')\n",
    "print(sorted([e1, e2, e3]))\n",
    "\n",
    "e1.notes.append('weekly shop')\n",
    "print(e1)\n",
    "print(e2.notes)  # [], independent of e1.notes\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "adv-0023",
   "metadata": {
    "language": "markdown",
    "tags": [
     "optional-enrichment"
    ]
   },
   "source": [
    "### Frozen Dataclasses\n",
    "\n",
    "**Optional enrichment.** Skip this subsection and the hashability/comparison extension that follows it for the required route; continue at namedtuple.\n",
    "\n",
    "`frozen=True` rejects normal field assignment and deletion. It does not freeze objects referenced by fields: a list field can still be mutated. With the default equality behavior, Python generates a hash method, but calling it still requires the participating field values to be hashable. The integer-valued `Color` below satisfies that requirement."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-adv-0023",
   "metadata": {
    "tags": [
     "optional-enrichment"
    ]
   },
   "source": [
    "```{index} frozen dataclass\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "adv-0024",
   "metadata": {
    "tags": [
     "optional-enrichment"
    ]
   },
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": "Color(r=255, g=0, b=0)\n4091835460043580556\n{Color(r=0, g=255, b=0), Color(r=255, g=0, b=0), Color(r=0, g=0, b=255)}\nFrozenInstanceError cannot assign to field 'r'\n"
    }
   ],
   "source": [
    "from dataclasses import dataclass\n",
    "\n",
    "@dataclass(frozen=True)\n",
    "class Color:\n",
    "    r: int\n",
    "    g: int\n",
    "    b: int\n",
    "\n",
    "red = Color(255, 0, 0)\n",
    "print(red)\n",
    "print(hash(red))   # hashable\n",
    "\n",
    "palette = {red, Color(0, 255, 0), Color(0, 0, 255)}\n",
    "print(palette)\n",
    "\n",
    "try:\n",
    "    red.r = 128    # raises FrozenInstanceError\n",
    "except Exception as e:\n",
    "    print(type(e).__name__, e)\n"
   ]
  },
  {
   "cell_type": "code",
   "id": "ch09-optional-currency-q",
   "metadata": {
    "tags": [
     "thebe-interactive",
     "optional-enrichment"
    ]
   },
   "execution_count": 19,
   "outputs": [],
   "source": [
    "### Exercise: Optional Frozen Records\n",
    "# Optional enrichment.\n",
    "# Define frozen Currency with code and symbol, put duplicate values in a set,\n",
    "# and catch a field reassignment error.\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "### Your code ends here.\n"
   ]
  },
  {
   "cell_type": "code",
   "id": "ch09-optional-currency-s",
   "metadata": {
    "tags": [
     "hide-input",
     "optional-enrichment"
    ]
   },
   "execution_count": 20,
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": "{Currency(code='USD', symbol='$'), Currency(code='CAD', symbol='C$')}\nFrozenInstanceError\n"
    }
   ],
   "source": [
    "### Solution\n",
    "from dataclasses import dataclass\n",
    "\n",
    "@dataclass(frozen=True)\n",
    "class Currency:\n",
    "    code: str\n",
    "    symbol: str\n",
    "\n",
    "usd = Currency('USD', '$')\n",
    "cad = Currency('CAD', 'C$')\n",
    "print({usd, cad, Currency('USD', '$')})   # the duplicate USD appears once\n",
    "\n",
    "try:\n",
    "    usd.symbol = 'US$'\n",
    "except Exception as e:\n",
    "    print(type(e).__name__)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "adv-0017",
   "metadata": {
    "language": "markdown",
    "tags": [
     "optional-enrichment"
    ]
   },
   "source": [
    "### Hashability and `__hash__`\n",
    "\n",
    "**Optional enrichment.** Read after Frozen Dataclasses; the required comparison lesson does not require hashing.\n",
    "\n",
    "```{index} hash method (__hash__), hashable\n",
    "```\n",
    "\n",
    "Defining value equality on an ordinary class without supplying a hash makes its instances unhashable. That is appropriate for the mutable core `Point`. A dictionary or set requires stable hashes: equal objects must have equal hashes, and the attributes used for equality and hashing must not change while an object is stored.\n",
    "\n",
    "The optional `HashPoint` below is a frozen dataclass. Its explicit `__hash__` shows the tuple-hashing rule; in this particular frozen dataclass Python could generate that method automatically. It uses a separate name so the core `Point` definition remains unchanged."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "adv-0018",
   "metadata": {
    "tags": [
     "optional-enrichment"
    ]
   },
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": "2\norigin-ish\n"
    }
   ],
   "source": [
    "from dataclasses import dataclass\n",
    "\n",
    "@dataclass(frozen=True)\n",
    "class HashPoint:\n",
    "    x: int\n",
    "    y: int\n",
    "\n",
    "    def __hash__(self):\n",
    "        return hash((self.x, self.y))\n",
    "\n",
    "p1 = HashPoint(1, 2)\n",
    "p2 = HashPoint(1, 2)\n",
    "p3 = HashPoint(3, 4)\n",
    "point_set = {p1, p2, p3}\n",
    "print(len(point_set))     # 2: equal objects collapse\n",
    "lookup = {p1: 'origin-ish', p3: 'far'}\n",
    "print(lookup[p2])         # origin-ish\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch09-total-ordering-extension",
   "metadata": {
    "tags": [
     "optional-enrichment"
    ]
   },
   "source": [
    "**Optional enrichment: deriving comparisons.**\n",
    "\n",
    "The\n",
    "`@functools.total_ordering` decorator **derives the missing ordering methods**\n",
    "from two definitions you supply:\n",
    "\n",
    "1. `__eq__`: define or inherit equality appropriate to the value policy; the decorator never derives it.\n",
    "2. **Any one** of `__lt__`, `__le__`, `__gt__`, or `__ge__`: the decorator\n",
    "   fills in the remaining three.\n",
    "\n",
    "| You define | Decorator derives |\n",
    "|---|---|\n",
    "| `__eq__` | Not generated; define or inherit the intended equality rule |\n",
    "| one of `__lt__` / `__le__` / `__gt__` / `__ge__` | the other three ordering methods |\n",
    "\n",
    "Using `__lt__` is conventional: `<` reads naturally as \"is *a* less than *b*?\",\n",
    "which maps cleanly onto sort order, but any of the four works.\n",
    "\n",
    "For example, if you define `__lt__` and `__eq__`, the decorator computes the\n",
    "other three from them:\n",
    "\n",
    "| Expression | Computed as |\n",
    "|---|---|\n",
    "| `a <= b` | `a < b or a == b` |\n",
    "| `a > b` | `not (a < b) and a != b` |\n",
    "| `a >= b` | `not (a < b)` |\n",
    "\n",
    "Every derived method calls `a.__lt__(b)` with `a` on the left, so it\n",
    "never needs the other object to define `<`.\n",
    "\n",
    "**Performance note:** because the derived methods add an extra function call\n",
    "layer, `@total_ordering` is marginally slower than writing all six methods\n",
    "explicitly. Consider hand-writing comparisons only if profiling identifies the generated methods as a bottleneck.\n",
    "\n",
    "Use equality and ordering rules that agree on ties. Comparing by `(amount, account)` makes two different accounts with the same amount distinguishable in both equality and ordering. A decorator cannot repair an inconsistent comparison policy.\n",
    "\n",
    "```{index} total_ordering decorator (@total_ordering)\n",
    "```\n"
   ]
  },
  {
   "cell_type": "code",
   "id": "ch09-optional-comparison-q",
   "metadata": {
    "tags": [
     "thebe-interactive",
     "optional-enrichment"
    ]
   },
   "execution_count": 22,
   "outputs": [],
   "source": [
    "### Exercise: Optional Comparison Extension\n",
    "# Optional enrichment; no later core example depends on this cell.\n",
    "# Define a frozen dataclass ValueTransaction with account: str and amount: float.\n",
    "# Use @total_ordering with explicit __eq__ and __lt__ (key: (amount, account)).\n",
    "# Define __hash__ from (account, amount).\n",
    "# Print equality, sorted values, max, and the size of a set with one duplicate.\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "### Your code ends here.\n"
   ]
  },
  {
   "cell_type": "code",
   "id": "ch09-optional-comparison-s",
   "metadata": {
    "tags": [
     "hide-input",
     "optional-enrichment"
    ]
   },
   "execution_count": 23,
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": "True\n[ValueTransaction(account='A-2', amount=20), ValueTransaction(account='A-1', amount=50), ValueTransaction(account='A-1', amount=50)]\nValueTransaction(account='A-1', amount=50)\n2\n"
    }
   ],
   "source": [
    "### Solution\n",
    "from dataclasses import dataclass\n",
    "from functools import total_ordering\n",
    "\n",
    "@total_ordering\n",
    "@dataclass(frozen=True)\n",
    "class ValueTransaction:\n",
    "    account: str\n",
    "    amount: float\n",
    "\n",
    "    def __eq__(self, other):\n",
    "        if not isinstance(other, ValueTransaction):\n",
    "            return NotImplemented\n",
    "        return (self.account, self.amount) == (other.account, other.amount)\n",
    "\n",
    "    def __lt__(self, other):\n",
    "        if not isinstance(other, ValueTransaction):\n",
    "            return NotImplemented\n",
    "        return (self.amount, self.account) < (other.amount, other.account)\n",
    "\n",
    "    def __hash__(self):\n",
    "        return hash((self.account, self.amount))\n",
    "\n",
    "v1 = ValueTransaction('A-1', 50)\n",
    "v2 = ValueTransaction('A-2', 20)\n",
    "v3 = ValueTransaction('A-1', 50)\n",
    "print(v1 == v3)\n",
    "print(sorted([v1, v2, v3]))\n",
    "print(max([v1, v2, v3]))\n",
    "print(len({v1, v2, v3}))\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "25a66497",
   "source": [
    "## namedtuple\n",
    "\n",
    "`namedtuple` from `collections` creates a lightweight, **immutable** data class in one line. It gives you named fields (like a regular class) plus the efficiency and unpacking of a plain tuple. Use it for simple, read-only data containers that don't need methods."
   ],
   "metadata": {}
  },
  {
   "cell_type": "markdown",
   "id": "ch09-record-choice",
   "metadata": {},
   "source": [
    "A named tuple is a tuple subclass: positional access and unpacking are part of its interface. A dataclass is a regular class with generated methods. Neither is a universal replacement for the other.\n",
    "\n",
    "| Decision | `namedtuple` | Default `@dataclass` |\n",
    "|---|---|---|\n",
    "| Named field access | Yes | Yes |\n",
    "| Positional indexing / unpacking | Tuple behavior | Not generated |\n",
    "| Reassign a field | Rejected | Allowed |\n",
    "| Generated representation | Includes type and named fields | Includes type and named fields |\n",
    "| Equality | Tuple values; can equal an ordinary tuple | Normally requires the same dataclass type |\n",
    "| Typical fit | Tuple-compatible read-only record | Record with annotations and evolving behavior |\n",
    "\n",
    "Both can hold mutable objects in their fields; tuple immutability prevents replacing a field, not mutating a referenced list. Both can have custom methods, although simple named tuples often need none."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-25a66497",
   "metadata": {},
   "source": [
    "```{index} namedtuple()\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "id": "1fa2979d",
   "source": [
    "from collections import namedtuple\n",
    "\n",
    "# namedtuple('ClassName', ['field1', 'field2', ...]) returns a new class\n",
    "Point = namedtuple('Point', ['x', 'y'])\n",
    "\n",
    "p = Point(3, 4)\n",
    "print(p)              # Point(x=3, y=4)\n",
    "print(p == Point(3, 4))   # True: value equality built in"
   ],
   "metadata": {
    "tags": []
   },
   "execution_count": 24,
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": "Point(x=3, y=4)\nTrue\n"
    }
   ]
  },
  {
   "cell_type": "code",
   "id": "50fc17e9",
   "source": [
    "from collections import namedtuple\n",
    "\n",
    "# Access by attribute name, by index, or by tuple unpacking: all work\n",
    "p = Point(3, 4)\n",
    "print(p.x, p.y)     # by name\n",
    "print(p[0], p[1])   # by index\n",
    "\n",
    "x, y = p            # tuple unpacking\n",
    "print(x, y)"
   ],
   "metadata": {},
   "execution_count": 25,
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": "3 4\n3 4\n3 4\n"
    }
   ]
  },
  {
   "cell_type": "code",
   "id": "d0dfe361",
   "source": [
    "# namedtuple instances are immutable: fields cannot be changed after creation\n",
    "try:\n",
    "    p.x = 10\n",
    "except AttributeError as e:\n",
    "    print(e)\n",
    "\n",
    "# But you can create a modified copy with _replace()\n",
    "p2 = p._replace(x=10)\n",
    "print(p2)   # Point(x=10, y=4)"
   ],
   "metadata": {},
   "execution_count": 26,
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": "can't set attribute\nPoint(x=10, y=4)\n"
    }
   ]
  },
  {
   "cell_type": "code",
   "id": "9f54fb45",
   "source": [
    "# namedtuple vs @dataclass: when to use which\n",
    "from dataclasses import dataclass\n",
    "\n",
    "# namedtuple: one line, immutable, no boilerplate: good for simple data records\n",
    "Player = namedtuple('Player', ['name', 'score'])\n",
    "p1 = Player('Alice', 95)\n",
    "print(p1)   # Player(name='Alice', score=95)\n",
    "\n",
    "# @dataclass: mutable by default, supports methods, type annotations\n",
    "@dataclass\n",
    "class PlayerDC:\n",
    "    name: str\n",
    "    score: float\n",
    "\n",
    "p2 = PlayerDC('Alice', 95)\n",
    "p2.score = 100   # mutation allowed\n",
    "print(p2)        # PlayerDC(name='Alice', score=100)"
   ],
   "metadata": {},
   "execution_count": 27,
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": "Player(name='Alice', score=95)\nPlayerDC(name='Alice', score=100)\n"
    }
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch09-record-prediction",
   "metadata": {},
   "source": [
    "Predict these comparisons from the table, then run them. A tuple-compatible record and a dataclass do not promise the same equality behavior."
   ]
  },
  {
   "cell_type": "code",
   "id": "ch09-record-prediction-code",
   "metadata": {},
   "execution_count": 28,
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": "True\nFalse\n"
    }
   ],
   "source": [
    "print(Player('Alice', 95) == ('Alice', 95))    # True\n",
    "print(PlayerDC('Alice', 95) == ('Alice', 95))  # False\n"
   ]
  },
  {
   "cell_type": "code",
   "id": "02ab83ea",
   "source": [
    "### Exercise: namedtuple\n",
    "# 1. Define a namedtuple called Employee with fields: name, department, salary.\n",
    "# 2. Create two Employee instances.\n",
    "# 3. Access the salary of the second employee by attribute name and by index.\n",
    "# 4. Try to change a field and confirm it raises an AttributeError.\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here."
   ],
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "code",
   "id": "f9682086",
   "source": [
    "### Solution\n",
    "from collections import namedtuple\n",
    "\n",
    "Employee = namedtuple('Employee', ['name', 'department', 'salary'])\n",
    "\n",
    "e1 = Employee('Alice', 'Engineering', 95000)\n",
    "e2 = Employee('Bob', 'Marketing', 78000)\n",
    "\n",
    "print(e1)\n",
    "print(e2.salary)    # by attribute name\n",
    "print(e2[2])        # by index: same field\n",
    "\n",
    "try:\n",
    "    e1.salary = 100000\n",
    "except AttributeError as e:\n",
    "    print(e)"
   ],
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "execution_count": null,
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": "Employee(name='Alice', department='Engineering', salary=95000)\n78000\n78000\ncan't set attribute\n"
    }
   ]
  },
  {
   "cell_type": "markdown",
   "id": "adv-0040",
   "metadata": {
    "language": "markdown"
   },
   "source": [
    "## Class vs. Instance Variables\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-adv-0040",
   "metadata": {},
   "source": [
    "```{index} class variable, instance variable, attribute shadowing\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "adv-0041",
   "metadata": {
    "language": "markdown"
   },
   "source": [
    "A **class variable** is defined directly in the class body, outside any method.\n",
    "It is shared across all instances. An **instance variable** is set on `self`\n",
    "inside a method and belongs only to that one object.\n",
    "\n",
    "Confusing the two is one of the most common OOP bugs in Python.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "id": "adv-0042",
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": "Canis lupus familiaris\nCanis lupus familiaris\nRex\nFido\n"
    }
   ],
   "source": [
    "class Dog:\n",
    "    species = 'Canis lupus familiaris'   # class variable: shared by all dogs\n",
    "\n",
    "    def __init__(self, name):\n",
    "        self.name = name                  # instance variable: unique per dog\n",
    "\n",
    "d1 = Dog('Rex')\n",
    "d2 = Dog('Fido')\n",
    "\n",
    "print(d1.species)    # 'Canis lupus familiaris'\n",
    "print(d2.species)    # same: shared\n",
    "print(d1.name)       # 'Rex'\n",
    "print(d2.name)       # 'Fido'\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "adv-0042a",
   "metadata": {},
   "source": [
    "The same idea fits banking. A bank name and a default transfer fee belong to the bank, not to one customer, so `AccountSettings` stores them as class variables. Updating a class variable through the class changes the value every instance sees. For these ordinary class defaults, reading first checks the instance, then its class. Assigning `b.transfer_fee = 4.50` creates an instance attribute that **shadows** the class value for `b`; it does not update `AccountSettings.transfer_fee`. Later class updates are visible only to instances that have not shadowed that name."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "id": "be36caa7",
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": "Phelps County Bank | Phelps County Bank\nInitial fee -> a: $2.50, b: $2.50\nAfter class update -> a: $3.00, b: $3.00\nAfter instance assignment -> a: $3.00, b: $4.50, class: $3.00\n"
    }
   ],
   "source": [
    "class AccountSettings:\n",
    "    bank_name = 'Phelps County Bank'   # shared by all instances\n",
    "    transfer_fee = 2.50               # shared default fee\n",
    "\n",
    "    def __init__(self, owner):\n",
    "        self.owner = owner\n",
    "\n",
    "a = AccountSettings('Ava')\n",
    "b = AccountSettings('Ben')\n",
    "\n",
    "print(a.bank_name, '|', b.bank_name)\n",
    "print(f'Initial fee -> a: ${a.transfer_fee:.2f}, b: ${b.transfer_fee:.2f}')\n",
    "\n",
    "# Update class variable: both instances see the new shared value\n",
    "AccountSettings.transfer_fee = 3.00\n",
    "print(f'After class update -> a: ${a.transfer_fee:.2f}, b: ${b.transfer_fee:.2f}')\n",
    "\n",
    "# Assign via one instance: creates an instance attribute (shadows class variable for that object only)\n",
    "b.transfer_fee = 4.50\n",
    "print(f'After instance assignment -> a: ${a.transfer_fee:.2f}, b: ${b.transfer_fee:.2f}, class: ${AccountSettings.transfer_fee:.2f}')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch09-shadowing-trace",
   "metadata": {},
   "source": [
    "| Stage | Class fee | `a.transfer_fee` | `b.transfer_fee` |\n",
    "|---|---:|---:|---:|\n",
    "| Initial class default | 2.50 | 2.50 | 2.50 |\n",
    "| Assign `AccountSettings.transfer_fee = 3.00` | 3.00 | 3.00 | 3.00 |\n",
    "| Assign `b.transfer_fee = 4.50` | 3.00 | 3.00 | 4.50 |\n",
    "\n",
    "A list created as `self.history = []` in `__init__` belongs to that instance, as in the earlier `TaskList` and dataclass examples. The following shared-list counterexample is optional; the required exercise uses independent instance lists."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "adv-ex-cv-q",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Class vs. Instance Variables\n",
    "#   1. Define a class SavingsAccount with a class variable interest_rate = 0.02\n",
    "#      and instance variables owner, balance, and history (a new empty list\n",
    "#      created in __init__).\n",
    "#   2. Create a1 = SavingsAccount('Ava', 1000) and a2 = SavingsAccount('Ben', 500).\n",
    "#   3. Set SavingsAccount.interest_rate = 0.03 and print both accounts' rates.\n",
    "#   4. Assign a1.interest_rate = 0.05, then print a1's rate, a2's rate,\n",
    "#      and SavingsAccount.interest_rate.\n",
    "#   5. Append 'opened' to a1.history and print both history lists.\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "### Your code ends here."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "id": "adv-ex-cv-s",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": "0.03 0.03\n0.05 0.03 0.03\n['opened'] []\n"
    }
   ],
   "source": [
    "### Solution\n",
    "class SavingsAccount:\n",
    "    interest_rate = 0.02              # class variable: shared default\n",
    "\n",
    "    def __init__(self, owner, balance):\n",
    "        self.owner = owner            # instance variables\n",
    "        self.balance = balance\n",
    "        self.history = []             # a new list for each account\n",
    "\n",
    "a1 = SavingsAccount('Ava', 1000)\n",
    "a2 = SavingsAccount('Ben', 500)\n",
    "\n",
    "SavingsAccount.interest_rate = 0.03\n",
    "print(a1.interest_rate, a2.interest_rate)\n",
    "\n",
    "a1.interest_rate = 0.05               # shadows the class variable on a1 only\n",
    "print(a1.interest_rate, a2.interest_rate, SavingsAccount.interest_rate)\n",
    "\n",
    "a1.history.append('opened')\n",
    "print(a1.history, a2.history)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "adv-0043",
   "metadata": {
    "language": "markdown",
    "tags": [
     "optional-enrichment"
    ]
   },
   "source": [
    "### The Mutation Trap\n",
    "\n",
    "**Optional enrichment.** No required example depends on running this shared-list counterexample.\n",
    "\n",
    "Assigning to a class variable **via an instance** creates a new instance\n",
    "variable that *shadows* the class variable; it does **not** change the class\n",
    "variable for all instances.\n",
    "\n",
    "But **mutating** a mutable class variable (like a list) *does* affect all\n",
    "instances, because no new variable is created.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-adv-0043",
   "metadata": {
    "tags": [
     "optional-enrichment"
    ]
   },
   "source": [
    "```{index} mutable class variable\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "id": "adv-0044",
   "metadata": {
    "tags": [
     "optional-enrichment"
    ]
   },
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": "99\n0\n0\n['event']\n['event']\n"
    }
   ],
   "source": [
    "class Counter:\n",
    "    count = 0            # class variable\n",
    "    history = []         # mutable class variable: danger zone\n",
    "\n",
    "    def __init__(self, name):\n",
    "        self.name = name\n",
    "\n",
    "a = Counter('a')\n",
    "b = Counter('b')\n",
    "\n",
    "# Reassignment via instance: creates a new instance variable on `a` only\n",
    "a.count = 99\n",
    "print(a.count)           # 99: instance variable on a\n",
    "print(b.count)           # 0 : class variable unchanged\n",
    "print(Counter.count)     # 0\n",
    "\n",
    "# Mutation via instance: modifies the shared class-level list\n",
    "a.history.append('event')\n",
    "print(b.history)         # ['event']: b sees the change!\n",
    "print(Counter.history)   # ['event']\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "adv-0045",
   "metadata": {
    "language": "markdown",
    "tags": [
     "optional-enrichment"
    ]
   },
   "source": [
    "**Rule of thumb:**\n",
    "\n",
    "- Use class variables for constants or data that *truly* belongs to the class (e.g., `species`, `MAX_SIZE`).\n",
    "- Use instance variables (set in `__init__`) for data that belongs to individual objects.\n",
    "- Never use a mutable class variable as a default container. Use `field(default_factory=list)` with `@dataclass`, or set the list in `__init__`.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "adv-0060",
   "metadata": {},
   "source": [
    "## Static and Class Methods\n",
    "\n",
    "Not every method needs an instance. Python provides two decorators\n",
    "for methods that are attached to the *class* itself rather than an instance:\n",
    "\n",
    "| Decorator | First parameter | Typical use |\n",
    "|-----------|-----------------|-------------|\n",
    "| `@staticmethod` | *(none)* | Utility function logically grouped with the class |\n",
    "| `@classmethod` | `cls` (the class itself) | Alternative constructors / factory methods |\n",
    "\n",
    "Both decorators come up naturally alongside class variables,\n",
    "because all three belong to the *class* rather than any one instance.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-adv-0060",
   "metadata": {},
   "source": [
    "```{index} staticmethod decorator (@staticmethod), classmethod decorator (@classmethod)\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "adv-0061",
   "metadata": {},
   "source": [
    "### Static Methods\n",
    "\n",
    "A **static method** is a regular function that lives inside a class for\n",
    "organizational reasons. It receives neither `self` nor `cls`,\n",
    "so it receives no implicit object or class. It can still use an object or class supplied explicitly as an argument; the decorator does not prohibit such access.\n",
    "\n",
    "A common use-case is a **validation or parsing helper** that supports\n",
    "other methods without depending on object state:"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-adv-0061",
   "metadata": {},
   "source": [
    "```{index} static method\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "id": "adv-0062",
   "metadata": {},
   "outputs": [],
   "source": [
    "class BankAccount:\n",
    "    \"\"\"A teaching account with controlled balance updates.\"\"\"\n",
    "\n",
    "    def __init__(self, owner=\"Unknown\", balance=0.0):\n",
    "        if balance < 0:\n",
    "            raise ValueError('Starting balance cannot be negative')\n",
    "        self.owner = owner\n",
    "        self._balance = balance\n",
    "\n",
    "    @property\n",
    "    def balance(self):\n",
    "        \"\"\"Current balance, read-only through the public interface.\"\"\"\n",
    "        return self._balance\n",
    "\n",
    "    def deposit(self, amount):\n",
    "        if amount <= 0:\n",
    "            raise ValueError('Deposit must be positive')\n",
    "        self._balance += amount\n",
    "        return self\n",
    "\n",
    "    def withdraw(self, amount):\n",
    "        if amount <= 0:\n",
    "            raise ValueError('Withdrawal must be positive')\n",
    "        if amount > self._balance:\n",
    "            raise ValueError('Insufficient funds')\n",
    "        self._balance -= amount\n",
    "        return self\n",
    "\n",
    "    def __str__(self):\n",
    "        return f\"BankAccount(owner={self.owner}, balance=${self._balance:.2f})\"\n",
    "\n",
    "    def __repr__(self):\n",
    "        return f\"BankAccount({self.owner!r}, {self._balance!r})\"\n",
    "\n",
    "    @staticmethod\n",
    "    def parse_record(s):\n",
    "        \"\"\"Parse an 'owner:balance' record into raw values.\"\"\"\n",
    "        owner, balance = s.split(':')\n",
    "        return owner, float(balance)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "adv-0063",
   "metadata": {},
   "source": [
    "Because `parse_record` is a static method, it has no `self` or `cls` parameter.\n",
    "It is a utility helper that can be called on the class directly:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "id": "adv-0064",
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": "BankAccount(owner=Taylor, balance=$348.00)\n"
    }
   ],
   "source": [
    "owner, balance = BankAccount.parse_record(\"Taylor:348.00\")\n",
    "acct = BankAccount(owner, balance)\n",
    "print(acct)   # BankAccount(owner=Taylor, balance=$348.00)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "adv-0065",
   "metadata": {},
   "source": [
    "### Class Methods\n",
    "\n",
    "A class method receives the calling class as its first argument, conventionally named `cls`. Writing `cls(...)` selects that class when constructing a result, including an inheriting subclass. It succeeds only if that class accepts the arguments being supplied.\n",
    "\n",
    "The owner/balance version below keeps the balance validation, read-only property, and update return values from {doc}`OOP Design and Methods <0901-oop-design>`. It does not use the numbered constructor from {doc}`The Four Pillars <0902-oop-pillars>`. The alternative constructors delegate validation to `__init__` instead of duplicating it."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-adv-0065",
   "metadata": {},
   "source": [
    "```{index} class method, cls\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "id": "adv-0066",
   "metadata": {},
   "outputs": [],
   "source": [
    "class BankAccount:\n",
    "    \"\"\"A teaching account with controlled balance updates.\"\"\"\n",
    "\n",
    "    def __init__(self, owner=\"Unknown\", balance=0.0):\n",
    "        if balance < 0:\n",
    "            raise ValueError('Starting balance cannot be negative')\n",
    "        self.owner = owner\n",
    "        self._balance = balance\n",
    "\n",
    "    @property\n",
    "    def balance(self):\n",
    "        \"\"\"Current balance, read-only through the public interface.\"\"\"\n",
    "        return self._balance\n",
    "\n",
    "    def deposit(self, amount):\n",
    "        if amount <= 0:\n",
    "            raise ValueError('Deposit must be positive')\n",
    "        self._balance += amount\n",
    "        return self\n",
    "\n",
    "    def withdraw(self, amount):\n",
    "        if amount <= 0:\n",
    "            raise ValueError('Withdrawal must be positive')\n",
    "        if amount > self._balance:\n",
    "            raise ValueError('Insufficient funds')\n",
    "        self._balance -= amount\n",
    "        return self\n",
    "\n",
    "    def __str__(self):\n",
    "        return f\"BankAccount(owner={self.owner}, balance=${self._balance:.2f})\"\n",
    "\n",
    "    def __repr__(self):\n",
    "        return f\"BankAccount({self.owner!r}, {self._balance!r})\"\n",
    "\n",
    "    @classmethod\n",
    "    def from_string(cls, s):\n",
    "        \"\"\"Create an account from an 'owner:balance' record.\"\"\"\n",
    "        owner, balance = s.split(':')\n",
    "        return cls(owner, float(balance))\n",
    "\n",
    "    @classmethod\n",
    "    def zero_balance(cls, owner):\n",
    "        return cls(owner, 0.0)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "id": "c27055c7",
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": "BankAccount(owner=Taylor, balance=$348.00)\n"
    }
   ],
   "source": [
    "acct1 = BankAccount.from_string(\"Taylor:348.00\")\n",
    "print(acct1)  # BankAccount(owner=Taylor, balance=$348.00)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "id": "adv-0067",
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": "BankAccount(owner=Casey, balance=$94.50)\nBankAccount(owner=Rin, balance=$0.00)\n"
    }
   ],
   "source": [
    "# Alternative constructors for the owner/balance version\n",
    "acct1 = BankAccount.from_string(\"Casey:94.50\")\n",
    "acct2 = BankAccount.zero_balance(\"Rin\")\n",
    "print(acct1)   # BankAccount(owner=Casey, balance=$94.50)\n",
    "print(acct2)   # BankAccount(owner=Rin, balance=$0.00)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "adv-0068",
   "metadata": {},
   "source": [
    "**When to use which:**\n",
    "\n",
    "| Question | `@staticmethod` | `@classmethod` |\n",
    "|---|---|---|\n",
    "| Implicit receiver | None | Calling class (`cls`) |\n",
    "| How can it obtain state? | Explicit arguments or named objects | Class receiver, plus explicit arguments |\n",
    "| Typical use here | Parse a record into values | Construct an instance of the calling class |\n",
    "\n",
    "A static method does not inherently hardcode a parent class. A class method is useful for a factory that should follow inheritance, but it cannot adapt automatically to an incompatible initializer. Preserve the factory contract or override the factory in a subclass that needs additional information."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch09-factory-compatibility",
   "metadata": {},
   "source": [
    "Compare two subclasses. The first inherits a compatible initializer. The second requires a `tier` that the inherited factory cannot supply. Predict the type of the first result and the exception for the second call."
   ]
  },
  {
   "cell_type": "code",
   "id": "ch09-factory-compatibility-code",
   "metadata": {},
   "execution_count": 41,
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": "True\nThe inherited factory cannot supply tier\n"
    }
   ],
   "source": [
    "class BasicAccount(BankAccount):\n",
    "    pass\n",
    "\n",
    "created = BasicAccount.from_string('Ava:100')\n",
    "print(type(created) is BasicAccount)  # True\n",
    "\n",
    "class TieredAccount(BankAccount):\n",
    "    def __init__(self, owner, balance, tier):\n",
    "        super().__init__(owner, balance)\n",
    "        self.tier = tier\n",
    "\n",
    "try:\n",
    "    TieredAccount.from_string('Ava:100')\n",
    "except TypeError:\n",
    "    print('The inherited factory cannot supply tier')\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "id": "adv-0069",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Class Methods\n",
    "#   Create a subclass ExtendedBankAccount(BankAccount) and add a class\n",
    "#   method from_balance_str(cls, owner, s) that parses a dollar string\n",
    "#   like \"12.34\" and returns a new account.\n",
    "#   Test:\n",
    "#       acct = ExtendedBankAccount.from_balance_str(\"Kai\", \"12.34\")\n",
    "#       print(acct)\n",
    "#       print(type(acct).__name__)   # ExtendedBankAccount\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "### Your code ends here.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "id": "adv-0070",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "BankAccount(owner=Kai, balance=$12.34)\n",
      "ExtendedBankAccount\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "class ExtendedBankAccount(BankAccount):\n",
    "    @classmethod\n",
    "    def from_balance_str(cls, owner, s):\n",
    "        \"\"\"Create account from a balance string like '12.34'.\"\"\"\n",
    "        return cls(owner, float(s))\n",
    "\n",
    "acct = ExtendedBankAccount.from_balance_str(\"Kai\", \"12.34\")\n",
    "print(acct)                  # __str__ is inherited from BankAccount\n",
    "print(type(acct).__name__)   # but cls built the subclass\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch09-0903-exercises",
   "metadata": {},
   "source": [
    "## Exercises\n",
    "\n",
    "This task combines a dataclass, operator overloading, and static and class methods in one record type."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ch09-0903-review-q",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Advanced OOP Review\n",
    "#   Build one record type that uses several features from this section.\n",
    "#   1. Import dataclass and define @dataclass(order=True) class Payment with\n",
    "#      fields amount: float and payer: str, in that order.\n",
    "#   2. Add a static method is_valid_amount(amount) that returns True when\n",
    "#      the amount is positive.\n",
    "#   3. Add a class method from_record(cls, record) that splits a record such as\n",
    "#      \"Ava:40.0\" at the colon, converts the amount to float, raises ValueError\n",
    "#      if is_valid_amount returns False, and returns cls(amount, payer).\n",
    "#   4. Add __add__ that returns a new Payment whose amount is the sum and whose\n",
    "#      payer is \"combined\". Return NotImplemented for any other operand type.\n",
    "#   5. Create p1 = Payment.from_record(\"Ava:40.0\") and\n",
    "#      p2 = Payment.from_record(\"Ben:25.5\"). Print the payers in sorted order,\n",
    "#      p1 + p2, and both original amounts.\n",
    "#   6. Call Payment.from_record(\"Cy:-5\") inside try/except ValueError and\n",
    "#      print \"Invalid amount\". Expected output:\n",
    "#      Sorted payers: ['Ben', 'Ava']\n",
    "#      Combined: Payment(amount=65.5, payer='combined')\n",
    "#      Originals: 40.0 25.5\n",
    "#      Invalid amount\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "### Your code ends here.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ch09-0903-review-s",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Sorted payers: ['Ben', 'Ava']\n",
      "Combined: Payment(amount=65.5, payer='combined')\n",
      "Originals: 40.0 25.5\n",
      "Invalid amount\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "from dataclasses import dataclass\n",
    "\n",
    "@dataclass(order=True)\n",
    "class Payment:\n",
    "    amount: float\n",
    "    payer: str\n",
    "\n",
    "    @staticmethod\n",
    "    def is_valid_amount(amount):\n",
    "        return amount > 0\n",
    "\n",
    "    @classmethod\n",
    "    def from_record(cls, record):\n",
    "        payer, amount = record.split(':')\n",
    "        amount = float(amount)\n",
    "        if not cls.is_valid_amount(amount):\n",
    "            raise ValueError('Amount must be positive')\n",
    "        return cls(amount, payer)\n",
    "\n",
    "    def __add__(self, other):\n",
    "        if not isinstance(other, Payment):\n",
    "            return NotImplemented\n",
    "        return Payment(self.amount + other.amount, 'combined')\n",
    "\n",
    "p1 = Payment.from_record('Ava:40.0')\n",
    "p2 = Payment.from_record('Ben:25.5')\n",
    "print('Sorted payers:', [p.payer for p in sorted([p1, p2])])\n",
    "print('Combined:', p1 + p2)\n",
    "print('Originals:', p1.amount, p2.amount)\n",
    "\n",
    "try:\n",
    "    Payment.from_record('Cy:-5')\n",
    "except ValueError:\n",
    "    print('Invalid amount')\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": ".venv (3.13.7)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.13.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
