{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "ee7da2b6-b3d2-4bad-928f-9c416b1eaec7",
   "metadata": {},
   "source": [
    "# OOP Design and Methods"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "0f6e77dd",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-26T18:56:57.470206Z",
     "iopub.status.busy": "2026-10-26T18:56:57.470094Z",
     "iopub.status.idle": "2026-10-26T18:56:57.999973Z",
     "shell.execute_reply": "2026-10-26T18:56:57.999535Z"
    },
    "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": "ch09-core-route",
   "metadata": {},
   "source": [
    "**Required core:** this notebook develops class definitions, instances, method binding, initialization, properties, and representations. Run demonstration cells in order. The banking contract is introduced below."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "contents",
   "metadata": {},
   "source": [
    "```{contents}\n",
    ":local:\n",
    ":depth: 2\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6da7aee2",
   "metadata": {},
   "source": [
    "## Why Object-Oriented Programming?\n",
    "\n",
    "Procedural programs often pass the same data through many separate functions. For example, the `deposit()` and `withdraw()` functions of a banking account management program share the parameters `owner`, `balance`, and `amount`.\n",
    "\n",
    "```python \n",
    "def deposit(owner, balance, amount):\n",
    "    return owner, balance + amount\n",
    "\n",
    "def withdraw(owner, balance, amount):\n",
    "    if amount > balance:\n",
    "        raise ValueError(\"Insufficient funds\")\n",
    "    return owner, balance - amount\n",
    "...\n",
    "...\n",
    "```\n",
    "\n",
    "\n",
    "You could save these functions in a file called `banking.py`, then run `import banking` in the Python shell to use them.\n",
    "\n",
    "```python\n",
    ">>> import banking\n",
    ">>> banking.deposit('Tom', 1000, 100)\n",
    "('Tom', 1100)\n",
    ">>> \n",
    "```\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-6da7aee2",
   "metadata": {},
   "source": [
    "```{index} object-oriented programming, object-oriented language, procedural programming, invariant\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8b7f27bd",
   "metadata": {},
   "source": [
    "This procedural style can work well for small scripts, but once the banking program starts to grow in the number of functions (which will eventually become non-trivial), it becomes harder to keep track of which data (the parameters) belongs together and which functions are allowed to change it.\n",
    "\n",
    "The same problem will occur when you model programs and systems based on real world things like library management information, student information system, or even game characters.\n",
    "\n",
    "**Object-Oriented Programming (OOP)** helps by organizing related data and behavior (functions/methods) into a **class**, which you then use to create **objects**. \n",
    "\n",
    "Key Benefits of Using OOP include:\n",
    "\n",
    "1. Modularity and Organization: OOP allows you to structure your code by breaking complex systems into smaller, manageable pieces (classes). This makes the code easier to navigate and maintain as projects grow.\n",
    "2. Code Reusability: Through inheritance, you can create a base class and reuse its logic in multiple child classes, adhering to the \"Don't Repeat Yourself\" (DRY) principle.\n",
    "3. Easier Debugging: Because data and the functions that manipulate it are bundled together in objects, it is often easier to isolate and fix errors without affecting the rest of the program.\n",
    "4. Real-World Modeling: OOP makes it intuitive to model real-world entities like \"Users,\" \"BankAccount\" objects, or \"GameCharacters\" by giving them specific properties (attributes) and actions (methods). \n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "465f66ad",
   "metadata": {},
   "source": [
    "Python is object-oriented at its core. While Python is multi-paradigm and allows for functional or procedural styles, OOP is its core foundation. In fact, everything in Python is an object, including integers and strings. You can see this in the values you already use: each one has **methods**, functions defined inside its class.\n",
    "\n",
    "| Value | Type (Class) | Example method |\n",
    "|---|---|---|\n",
    "| `7` | `int` | `bit_length()` |\n",
    "| `\"hello\"` | `str` | `upper()`, `split()` |\n",
    "| `[1, 2, 3]` | `list` | `append()`, `sort()` |\n",
    "| `{'a': 1}` | `dict` | `keys()`, `get()` |\n",
    "\n",
    "When you call `[1, 2, 3].sort()`, you are calling a method on a `list` object. This chapter applies the same idea to classes you define.\n",
    "\n",
    "Note the column header **Type (Class)**: in Python 3, the two words mean the same thing. Every class you define *is* a type, and every built-in type like `str` or `list` *is* a class. The terms are used interchangeably throughout this chapter."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch09-class-design",
   "metadata": {},
   "source": [
    "Before writing a class, identify the state it owns and the operations callers need. For `BankAccount`, the owner and balance belong together. Its operations should preserve an **invariant**, a condition that remains true after construction and every successful public operation.\n",
    "\n",
    "| Design decision | Account contract |\n",
    "|---|---|\n",
    "| State | Owner and balance |\n",
    "| Initial state | Balance is nonnegative |\n",
    "| Public updates | Deposit a positive amount; withdraw a positive amount within the balance |\n",
    "| Failure | Reject invalid amounts before changing the balance |\n",
    "| Observation | Read `balance`; use `str()` or `repr()` to inspect the object |\n",
    "\n",
    "Functions can validate too, but with the procedural version the caller holds `owner` and `balance` as loose variables: any line of code can set `balance = -500` between calls, or pass one account's balance with another's owner. A class keeps the state inside one object and routes every change through its methods, so the invariant is checked wherever the balance changes. A small procedural script remains a reasonable choice when only a few lines touch the data and there is a single copy of it."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "796bfff2",
   "metadata": {},
   "source": [
    "## Classes and Instances\n",
    "\n",
    "A **class** is a blueprint that defines data and behavior. An **instance** is one concrete **object** created from that blueprint.\n",
    "\n",
    "Think of a class as a cookie cutter and each instance as an individual cookie. The cutter defines the shape; every cookie produced from it is a separate object with its own toppings (attributes).\n",
    "\n",
    "| Term | Meaning | Cookie analogy |\n",
    "|---|---|---|\n",
    "| Class | Blueprint / template | The cookie cutter |\n",
    "| Instance | One object made from the class | A specific cookie |\n",
    "| Attribute | Data stored on the instance | Icing color, sprinkles |\n",
    "| Method | Function that belongs to the class | `decorate()`, `eat()` |\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-796bfff2",
   "metadata": {},
   "source": [
    "```{index} class, instance, class definition, attribute\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bb77d3be",
   "metadata": {},
   "source": [
    "The basic syntax for defining a class in Python looks like this:\n",
    "\n",
    "```python\n",
    "class ClassName:\n",
    "    \"\"\"Optional docstring describing the class.\"\"\"\n",
    "\n",
    "    def __init__(self, attribute1, attribute2):   # initializer\n",
    "        self.attribute1 = attribute1              # store data on the instance\n",
    "        self.attribute2 = attribute2\n",
    "\n",
    "    def method_name(self, other_param):           # instance method\n",
    "        # self always refers to the current instance\n",
    "        return self.attribute1 + other_param\n",
    "```\n",
    "\n",
    "\n",
    "- `class ClassName:` declares a new class (use PascalCase by convention)\n",
    "- `__init__`: the **initializer** Python calls on the new instance. Calling the class creates the object; `__init__` sets its initial state and must return `None`\n",
    "- `self`: the instance itself; Python passes it automatically\n",
    "- `def method_name(self, ...)`: any method that operates on the instance"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d27e2fd3",
   "metadata": {},
   "source": [
    "Here is a simple `Point` class. As you can see, it creates 2D points and can calculate the distance between two points."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "8808b80b",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-26T18:56:58.001915Z",
     "iopub.status.busy": "2026-10-26T18:56:58.001780Z",
     "iopub.status.idle": "2026-10-26T18:56:58.003708Z",
     "shell.execute_reply": "2026-10-26T18:56:58.003312Z"
    }
   },
   "outputs": [],
   "source": [
    "class Point:\n",
    "    \"\"\"Represent a 2D point with x and y coordinates.\"\"\"\n",
    "\n",
    "    def __init__(self, x, y):\n",
    "        self.x = x\n",
    "        self.y = y\n",
    "\n",
    "    def distance_to(self, other):\n",
    "        \"\"\"Return Euclidean distance from this point to another Point.\"\"\"\n",
    "        return ((self.x - other.x) ** 2 + (self.y - other.y) ** 2) ** 0.5\n",
    "\n",
    "### Point has no __str__ method yet, so printing a Point shows Python's default\n",
    "### representation, which is not very informative. The __str__ Method subsection\n",
    "### later in this section explains the commented-out method below.\n",
    "   \n",
    "    # def __str__(self):\n",
    "    #     return f\"Point({self.x}, {self.y})\""
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e189b75e",
   "metadata": {},
   "source": [
    "\n",
    "You create instances by calling the class like a function:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "5320f1dd",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-26T18:56:58.004853Z",
     "iopub.status.busy": "2026-10-26T18:56:58.004777Z",
     "iopub.status.idle": "2026-10-26T18:56:58.006675Z",
     "shell.execute_reply": "2026-10-26T18:56:58.006347Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<__main__.Point object at 0x108af97f0>\n",
      "<__main__.Point object at 0x10fc5b390>\n",
      "5.0\n"
     ]
    }
   ],
   "source": [
    "p = Point(3, 4)   # one point object\n",
    "q = Point(0, 0)   # another point object\n",
    "\n",
    "print(p)\n",
    "print(q)\n",
    "\n",
    "print(p.distance_to(q))\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7c81a474",
   "metadata": {},
   "source": [
    "Even though the points come from the same class, they are independent objects. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "300eee75",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-26T18:56:58.007764Z",
     "iopub.status.busy": "2026-10-26T18:56:58.007695Z",
     "iopub.status.idle": "2026-10-26T18:56:58.009349Z",
     "shell.execute_reply": "2026-10-26T18:56:58.008987Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "False\n",
      "False\n"
     ]
    }
   ],
   "source": [
    "r = Point(3, 4)   # a third point object with the same coordinates as p\n",
    "s = Point(3, 4)   # a fourth point object with the same coordinates as p and r\n",
    "print(r is s)\n",
    "print(r == s)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch09-identity-forward",
   "metadata": {},
   "source": [
    "Both results are false here: `r` and `s` are separate instances, and this class has not defined value equality. Equal coordinates do not yet make two points compare equal. {doc}`Advanced OOP Topics <0903-oop-advanced>` develops `__eq__`; `is` will continue to test identity."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d50292f5",
   "metadata": {},
   "source": [
    "### Custom and Built-in Types"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-d50292f5",
   "metadata": {},
   "source": [
    "```{index} isinstance(), type(), user-defined type\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "243a25b6",
   "metadata": {},
   "source": [
    "Two built-in tools let you inspect objects:\n",
    "\n",
    "- `type(obj)`: returns the class of the object\n",
    "- `isinstance(obj, SomeClass)`: returns `True` if `obj` is an instance of that class (or a subclass)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6c8ef72d",
   "metadata": {},
   "source": [
    "Compare a `Point` instance with built-in values.\n",
    "\n",
    "**Takeaway:** user-defined class instances behave like built-in objects under `type()` and `isinstance()`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "8ad2da99",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-26T18:56:58.010444Z",
     "iopub.status.busy": "2026-10-26T18:56:58.010385Z",
     "iopub.status.idle": "2026-10-26T18:56:58.012420Z",
     "shell.execute_reply": "2026-10-26T18:56:58.012072Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class '__main__.Point'>\n",
      "True\n",
      "True\n",
      "False\n",
      "<class 'str'>\n",
      "True\n",
      "True\n",
      "False\n"
     ]
    }
   ],
   "source": [
    "p = Point(3, 4)\n",
    "\n",
    "print(type(p))                      ### <class '__main__.Point'>\n",
    "print(type(p) is Point)             ### True\n",
    "print(isinstance(p, Point))         ### True\n",
    "print(isinstance(p, str))           ### False\n",
    "\n",
    "### Custom types/classes and built-in types work the same way\n",
    "print(type(\"hello\"))                ### <class 'str'>\n",
    "print(type(\"hello\") is str)         ### True\n",
    "print(isinstance(42, int))          ### True\n",
    "print(isinstance(42, float))        ### False"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "411e9bea",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-26T18:56:58.013694Z",
     "iopub.status.busy": "2026-10-26T18:56:58.013611Z",
     "iopub.status.idle": "2026-10-26T18:56:58.015335Z",
     "shell.execute_reply": "2026-10-26T18:56:58.014967Z"
    },
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Classes vs Instances\n",
    "#   1. Define a class `Book` with `title` and `author` in `__init__`.\n",
    "#   2. Create two instances with different titles.\n",
    "#   3. Print each instance's title and author on separate lines.\n",
    "#   4. Print `book1 is book2` to verify they are different objects.\n",
    "#   5. Print `isinstance(book1, Book)`.\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "c83d985d",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-26T18:56:58.016254Z",
     "iopub.status.busy": "2026-10-26T18:56:58.016197Z",
     "iopub.status.idle": "2026-10-26T18:56:58.018098Z",
     "shell.execute_reply": "2026-10-26T18:56:58.017774Z"
    },
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Python Design - A. Chen\n",
      "Data Workflows - B. Diaz\n",
      "False\n",
      "True\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "class Book:\n",
    "    def __init__(self, title, author):\n",
    "        self.title = title\n",
    "        self.author = author\n",
    "\n",
    "book1 = Book(\"Python Design\", \"A. Chen\")\n",
    "book2 = Book(\"Data Workflows\", \"B. Diaz\")\n",
    "\n",
    "print(book1.title, \"-\", book1.author)\n",
    "print(book2.title, \"-\", book2.author)\n",
    "print(book1 is book2)\n",
    "print(isinstance(book1, Book))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e9d9f3d1",
   "metadata": {},
   "source": [
    "## A Calculator Class\n",
    "\n",
    "The `Point` class above is your first class: it stores two values and has one method. Here is a second sample class, `CalcTwo`, a calculator that performs operations on **two input numbers**. Its methods also use **`self`** because they belong to an instance, and the class shows that one class can contain several methods."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-e9d9f3d1",
   "metadata": {},
   "source": [
    "```{index} self, method call\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "63e1d465",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-26T18:56:58.019151Z",
     "iopub.status.busy": "2026-10-26T18:56:58.019086Z",
     "iopub.status.idle": "2026-10-26T18:56:58.021224Z",
     "shell.execute_reply": "2026-10-26T18:56:58.020904Z"
    }
   },
   "outputs": [],
   "source": [
    "class CalcTwo:\n",
    "    \"\"\"Represents a calculator for operations on two numbers.\"\"\"\n",
    "\n",
    "    def __init__(self):\n",
    "        self.last_result = None  # Keep track of the most recent calculation\n",
    "\n",
    "    def add(self, a, b):\n",
    "        \"\"\"Return a + b.\"\"\"\n",
    "        self.last_result = a + b  # Save result on this instance\n",
    "        return self.last_result\n",
    "\n",
    "    def subtract(self, a, b):\n",
    "        \"\"\"Return a - b.\"\"\"\n",
    "        self.last_result = a - b\n",
    "        return self.last_result\n",
    "\n",
    "    def multiply(self, a, b):\n",
    "        \"\"\"Return a * b.\"\"\"\n",
    "        self.last_result = a * b\n",
    "        return self.last_result\n",
    "\n",
    "    def divide(self, a, b):\n",
    "        \"\"\"Return a / b.\"\"\"\n",
    "        if b == 0:\n",
    "            raise ValueError(\"Cannot divide by zero\")  # Avoid undefined operation\n",
    "        self.last_result = a / b\n",
    "        return self.last_result\n",
    "\n",
    "    def __str__(self):\n",
    "        return f\"CalcTwo(last_result={self.last_result})\""
   ]
  },
  {
   "cell_type": "markdown",
   "id": "53a320ac",
   "metadata": {},
   "source": [
    "Key parts of the code above:\n",
    "\n",
    "| Part | What it does |\n",
    "|---|---|\n",
    "| `class CalcTwo:` | Declares the class |\n",
    "| `def __init__(self):` | Initializer; runs on the new instance when you call `CalcTwo()` |\n",
    "| `def __str__(self):` | Controls what `print()` shows; Python calls it automatically |\n",
    "| **`self`** | <span style=\"color:darkred\">The instance being created or used; Python passes it automatically</span> |\n",
    "| `self.last_result` | Stores the most recent result on this instance |\n",
    "| `def add(self, a, b):` | Returns the sum of two numbers |\n",
    "| `def subtract(self, a, b):` | Returns the difference of two numbers |\n",
    "| `def multiply(self, a, b):` | Returns the product of two numbers |\n",
    "| `def divide(self, a, b):` | Returns the quotient of two numbers |\n",
    "\n",
    "- `__init__()`: The **initializer**, called automatically on a new `CalcTwo` instance.\n",
    "- `__str__()`: Returns a readable string representation of the calculator state.\n",
    "- Arithmetic methods: each method takes two numbers and returns a computed result.\n",
    "- `last_result`: lets each instance remember its own most recent calculation."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "39d319da",
   "metadata": {},
   "source": [
    "Now create two instances of `CalcTwo`: `c1` and `c2`. After creating them, you can:\n",
    "\n",
    "1. access data in the object (e.g., `c1.last_result`)\n",
    "2. make **method calls** with two numbers (e.g., `c1.add(5, 2)`, `c1.subtract(9, 4)`)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "2eb9374d",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-26T18:56:58.022348Z",
     "iopub.status.busy": "2026-10-26T18:56:58.022289Z",
     "iopub.status.idle": "2026-10-26T18:56:58.024103Z",
     "shell.execute_reply": "2026-10-26T18:56:58.023815Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "15\n",
      "7\n",
      "24\n",
      "7.0\n",
      "24\n",
      "7.0\n",
      "CalcTwo(last_result=24)\n"
     ]
    }
   ],
   "source": [
    "c1 = CalcTwo()\n",
    "c2 = CalcTwo()\n",
    "\n",
    "print(c1.add(10, 5))           # 15\n",
    "print(c1.subtract(10, 3))      # 7\n",
    "print(c1.multiply(4, 6))       # 24\n",
    "print(c2.divide(21, 3))        # 7.0\n",
    "print(c1.last_result)          # 24 (independent from c2)\n",
    "print(c2.last_result)          # 7.0\n",
    "\n",
    "print(c1)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch09-calc-state-trace",
   "metadata": {},
   "source": [
    "Each method receives a particular object as `self`. Trace the calls above by recording both instances' state; a call on one calculator does not update the other.\n",
    "\n",
    "| After call | Returned value | `c1.last_result` | `c2.last_result` |\n",
    "|---|---:|---:|---:|\n",
    "| `c1.add(10, 5)` | 15 | 15 | `None` |\n",
    "| `c1.subtract(10, 3)` | 7 | 7 | `None` |\n",
    "| `c1.multiply(4, 6)` | 24 | 24 | `None` |\n",
    "| `c2.divide(21, 3)` | 7.0 | 24 | 7.0 |\n",
    "\n",
    "The return value and the stored attribute happen to agree here, but they are different parts of the method's interface. A method can return a value, change state, do both, or do neither."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d28be810",
   "metadata": {},
   "source": [
    "### Defining Methods\n",
    "\n",
    "`CalcTwo.add` is a **method**: a function defined inside a class. To see what that adds, compare it with a standalone function that does the same job. The function receives the calculator as an ordinary parameter, `calc`."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-d28be810",
   "metadata": {},
   "source": [
    "```{index} method, self\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "557f34cd",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-26T18:56:58.025147Z",
     "iopub.status.busy": "2026-10-26T18:56:58.025078Z",
     "iopub.status.idle": "2026-10-26T18:56:58.026496Z",
     "shell.execute_reply": "2026-10-26T18:56:58.026204Z"
    }
   },
   "outputs": [],
   "source": [
    "def add_two(calc, a, b):\n",
    "    calc.last_result = a + b\n",
    "    return calc.last_result"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bc151163",
   "metadata": {},
   "source": [
    "The method version, which `CalcTwo` already defines, moves the same logic inside the class and renames the first parameter from `calc` to `self`. The name `self` is a convention, not a syntax rule."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "14398fe0",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-04-27T03:21:51.928326Z",
     "iopub.status.busy": "2026-04-27T03:21:51.928277Z",
     "iopub.status.idle": "2026-04-27T03:21:51.929409Z",
     "shell.execute_reply": "2026-04-27T03:21:51.929268Z"
    }
   },
   "source": [
    "```python\n",
    "class CalcTwo:\n",
    "    def add(self, a, b):\n",
    "        self.last_result = a + b\n",
    "        return self.last_result\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0832ef86",
   "metadata": {},
   "source": [
    "To call either version, first create a `CalcTwo` object."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "4e39be0d",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-26T18:56:58.027491Z",
     "iopub.status.busy": "2026-10-26T18:56:58.027432Z",
     "iopub.status.idle": "2026-10-26T18:56:58.028953Z",
     "shell.execute_reply": "2026-10-26T18:56:58.028523Z"
    }
   },
   "outputs": [],
   "source": [
    "calc = CalcTwo()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "ch09-add-two-call",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-26T18:56:58.029783Z",
     "iopub.status.busy": "2026-10-26T18:56:58.029729Z",
     "iopub.status.idle": "2026-10-26T18:56:58.032158Z",
     "shell.execute_reply": "2026-10-26T18:56:58.031794Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "13"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "add_two(calc, 9, 4)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6231a828",
   "metadata": {},
   "source": [
    "The standalone function takes the calculator as an explicit argument. The method can be called the same way, through the class; this function-style syntax is less common."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "474799ba",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-26T18:56:58.033108Z",
     "iopub.status.busy": "2026-10-26T18:56:58.033055Z",
     "iopub.status.idle": "2026-10-26T18:56:58.034720Z",
     "shell.execute_reply": "2026-10-26T18:56:58.034417Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "13"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "CalcTwo.add(calc, 9, 4)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e04351f1",
   "metadata": {},
   "source": [
    "In this version, `CalcTwo` is the class name, `add` is the method name, and `calc` is passed explicitly as the first argument.\n",
    "The second (and more idiomatic) way is method syntax:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "0e3bfcab",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-26T18:56:58.035802Z",
     "iopub.status.busy": "2026-10-26T18:56:58.035720Z",
     "iopub.status.idle": "2026-10-26T18:56:58.037570Z",
     "shell.execute_reply": "2026-10-26T18:56:58.037228Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "13"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "calc.add(9, 4)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "342456f0",
   "metadata": {},
   "source": [
    "Both calls return the same result.\n",
    "The receiver object is assigned to the first parameter, so inside the method, `self` refers to the same object as `calc`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "56eec25f",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-26T18:56:58.038554Z",
     "iopub.status.busy": "2026-10-26T18:56:58.038489Z",
     "iopub.status.idle": "2026-10-26T18:56:58.040226Z",
     "shell.execute_reply": "2026-10-26T18:56:58.039892Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "13\n"
     ]
    }
   ],
   "source": [
    "print(calc.last_result)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "592a372c",
   "metadata": {},
   "source": [
    "In method syntax, `calc` is the object the method is invoked on (the **receiver**).\n",
    "\n",
    "Regardless of syntax, behavior is the same:\n",
    "`CalcTwo.add(calc, 9, 4)` and `calc.add(9, 4)` both use the same method implementation."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch09-bound-md",
   "metadata": {},
   "source": [
    "A method is also a value. Without parentheses, `calc.add` refers to a **bound method**: the method together with the object it belongs to. You can store it in a variable and call it later. With parentheses, `calc.add(2, 3)` calls it immediately."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-ch09-bound",
   "metadata": {},
   "source": [
    "```{index} bound method\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "ch09-bound-code",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-26T18:56:58.041166Z",
     "iopub.status.busy": "2026-10-26T18:56:58.041110Z",
     "iopub.status.idle": "2026-10-26T18:56:58.042533Z",
     "shell.execute_reply": "2026-10-26T18:56:58.042264Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "5\n",
      "5\n"
     ]
    }
   ],
   "source": [
    "action = calc.add          # no parentheses: store the bound method\n",
    "result = action(2, 3)      # call it later, just like calc.add(2, 3)\n",
    "print(result)              # 5\n",
    "print(calc.last_result)    # 5, because action is bound to calc"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch09-bound-md2",
   "metadata": {},
   "source": [
    "Class methods, introduced in {doc}`Advanced OOP Topics <0903-oop-advanced>`, can be stored and called later in the same way."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "8f6b6b79",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-26T18:56:58.043551Z",
     "iopub.status.busy": "2026-10-26T18:56:58.043495Z",
     "iopub.status.idle": "2026-10-26T18:56:58.044973Z",
     "shell.execute_reply": "2026-10-26T18:56:58.044613Z"
    },
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Defining Methods\n",
    "#   This standalone function computes a rectangle's area:\n",
    "#       def rect_area(rect):\n",
    "#           return rect.width * rect.height\n",
    "#   1. Define a class Rectangle whose __init__(self, width, height) stores both values.\n",
    "#   2. Rewrite rect_area as a method area(self) inside the class.\n",
    "#   3. Create r = Rectangle(3, 5) and call the method both ways:\n",
    "#      Rectangle.area(r) and r.area().\n",
    "#   4. Store the bound method r.area in a variable, then call the variable.\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "### Your code ends here."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "4c14e492",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-26T18:56:58.045935Z",
     "iopub.status.busy": "2026-10-26T18:56:58.045866Z",
     "iopub.status.idle": "2026-10-26T18:56:58.047763Z",
     "shell.execute_reply": "2026-10-26T18:56:58.047439Z"
    },
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "15\n",
      "15\n",
      "15\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "class Rectangle:\n",
    "    def __init__(self, width, height):\n",
    "        self.width = width\n",
    "        self.height = height\n",
    "\n",
    "    def area(self):\n",
    "        return self.width * self.height\n",
    "\n",
    "r = Rectangle(3, 5)\n",
    "print(Rectangle.area(r))   # 15, function-style call\n",
    "print(r.area())            # 15, method syntax\n",
    "\n",
    "get_area = r.area          # bound method\n",
    "print(get_area())          # 15"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2a42bfd4",
   "metadata": {},
   "source": [
    "## A BankAccount Class\n",
    "\n",
    "This banking version uses the contract introduced above: a nonnegative starting balance, positive deposits and withdrawals, a read-only public balance, and validation before mutation. Both update methods return `self`, so callers may keep the account result or ignore it. Returning `self` does not create a second account.\n",
    "\n",
    "The class combines three **special methods**, also called **dunder methods** because their names begin and end with double underscores, with one property:\n",
    "\n",
    "| Feature | Used by | Purpose |\n",
    "|---|---|---|\n",
    "| `__init__` | `BankAccount(...)` | Initialize the new object's state |\n",
    "| `__str__` | `str()`, `print()` | Human-readable text |\n",
    "| `__repr__` | `repr()`, interactive display | Diagnostic, ideally reconstructable text |\n",
    "| `@property` | `acct.balance` | Read through attribute syntax without a public setter |\n",
    "\n",
    "A property is not a dunder method. The complete definition below lets you see how these features fit together; the following subsections explain each feature."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-2a42bfd4",
   "metadata": {},
   "source": [
    "```{index} special method, dunder method\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "c529c7ad",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-26T18:56:58.048762Z",
     "iopub.status.busy": "2026-10-26T18:56:58.048698Z",
     "iopub.status.idle": "2026-10-26T18:56:58.051061Z",
     "shell.execute_reply": "2026-10-26T18:56:58.050813Z"
    }
   },
   "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"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "110502f3",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-26T18:56:58.052085Z",
     "iopub.status.busy": "2026-10-26T18:56:58.052026Z",
     "iopub.status.idle": "2026-10-26T18:56:58.053503Z",
     "shell.execute_reply": "2026-10-26T18:56:58.053132Z"
    }
   },
   "outputs": [],
   "source": [
    "acct1 = BankAccount(\"Ava\", 945.30)\n",
    "acct2 = BankAccount(\"Max\", 500.00)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch09-account-state",
   "metadata": {},
   "source": [
    "Predict the balance after each operation, then run the cell. Successful updates return the same account object. A rejected withdrawal raises an exception before any subtraction, preserving the balance."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "ch09-account-state-code",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-26T18:56:58.054427Z",
     "iopub.status.busy": "2026-10-26T18:56:58.054369Z",
     "iopub.status.idle": "2026-10-26T18:56:58.056210Z",
     "shell.execute_reply": "2026-10-26T18:56:58.055949Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "150 True\n",
      "Insufficient funds\n",
      "150\n",
      "Deposit must be positive\n",
      "150\n"
     ]
    }
   ],
   "source": [
    "account = BankAccount('Ava', 100)\n",
    "returned = account.deposit(50)\n",
    "print(account.balance, returned is account)  # 150 True\n",
    "try:\n",
    "    account.withdraw(200)\n",
    "except ValueError as error:\n",
    "    print(error)  # Insufficient funds\n",
    "print(account.balance)  # 150, unchanged\n",
    "try:\n",
    "    account.deposit(-20)\n",
    "except ValueError as error:\n",
    "    print(error)  # Deposit must be positive\n",
    "print(account.balance)  # 150, unchanged\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch09-account-state-feedback",
   "metadata": {},
   "source": [
    "| Operation | Balance before | Balance after | Result |\n",
    "|---|---:|---:|---|\n",
    "| `deposit(50)` | 100 | 150 | The same account object |\n",
    "| `withdraw(200)` | 150 | 150 | `ValueError` |\n",
    "| `deposit(-20)` | 150 | 150 | `ValueError` |"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2fbe6bba",
   "metadata": {},
   "source": [
    "### The `__init__` Method\n",
    "\n",
    "The most special of the special methods is `__init__`, so-called because it\n",
    "initializes the attributes of a new object. Here is the `__init__` method\n",
    "from the `BankAccount` class:\n",
    "\n",
    "```python\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",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-2fbe6bba",
   "metadata": {},
   "source": [
    "```{index} initializer method (__init__), constructor call\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "78515e85",
   "metadata": {},
   "source": [
    "When you instantiate a `BankAccount` object, Python invokes `__init__` automatically\n",
    "and passes along the arguments. So you can create an object and set its initial balance\n",
    "at the same time."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "id": "599bb4b4",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-26T18:56:58.057355Z",
     "iopub.status.busy": "2026-10-26T18:56:58.057301Z",
     "iopub.status.idle": "2026-10-26T18:56:58.058721Z",
     "shell.execute_reply": "2026-10-26T18:56:58.058442Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "BankAccount(owner=Ava, balance=$94.00)\n"
     ]
    }
   ],
   "source": [
    "account = BankAccount(\"Ava\", 94.00)\n",
    "print(account)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f22ccfa7",
   "metadata": {},
   "source": [
    "Both parameters are optional. If you call `BankAccount` with no arguments,\n",
    "you get the default values (`\"Unknown\"` and `0.0`)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "c0b4a924",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-26T18:56:58.059558Z",
     "iopub.status.busy": "2026-10-26T18:56:58.059492Z",
     "iopub.status.idle": "2026-10-26T18:56:58.061028Z",
     "shell.execute_reply": "2026-10-26T18:56:58.060650Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "BankAccount(owner=Unknown, balance=$0.00)\n"
     ]
    }
   ],
   "source": [
    "account = BankAccount()\n",
    "print(account)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "944ba44c",
   "metadata": {},
   "source": [
    "If you provide one argument, it overrides `owner`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "id": "40b10f78",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-26T18:56:58.062056Z",
     "iopub.status.busy": "2026-10-26T18:56:58.061993Z",
     "iopub.status.idle": "2026-10-26T18:56:58.063422Z",
     "shell.execute_reply": "2026-10-26T18:56:58.063126Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "BankAccount(owner=Sam, balance=$0.00)\n"
     ]
    }
   ],
   "source": [
    "account = BankAccount(\"Sam\")\n",
    "print(account)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4cc47eda",
   "metadata": {},
   "source": [
    "If you provide two arguments, they override `owner` and `balance`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "id": "2e759bbb",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-26T18:56:58.064267Z",
     "iopub.status.busy": "2026-10-26T18:56:58.064217Z",
     "iopub.status.idle": "2026-10-26T18:56:58.065627Z",
     "shell.execute_reply": "2026-10-26T18:56:58.065337Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "BankAccount(owner=Sam, balance=$45.00)\n"
     ]
    }
   ],
   "source": [
    "account = BankAccount(\"Sam\", 45.00)\n",
    "print(account)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "89af1327",
   "metadata": {},
   "source": [
    "When you write a new class, start with `__init__`, which makes objects easy\n",
    "to create, and `__str__`, which is useful for debugging."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f4df6ae6",
   "metadata": {},
   "source": [
    "### Properties\n",
    "\n",
    "The `@property` decorator lets you define a method that behaves like an attribute.\n",
    "This is useful when you want controlled read-only (or validated) access to a\n",
    "value stored on the object, *without* changing how callers access it.\n",
    "\n",
    "Here is the `balance` property from the `BankAccount` class:\n",
    "\n",
    "```python\n",
    "    @property\n",
    "    def balance(self):\n",
    "        \"\"\"Current balance, read-only through the public interface.\"\"\"\n",
    "        return self._balance\n",
    "```\n",
    "\n",
    "The underscore in `_balance` signals that it is an *internal* attribute: callers\n",
    "should use the `balance` property rather than accessing `_balance` directly."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-f4df6ae6",
   "metadata": {},
   "source": [
    "```{index} property decorator (@property)\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "id": "42572d7e",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-26T18:56:58.066626Z",
     "iopub.status.busy": "2026-10-26T18:56:58.066561Z",
     "iopub.status.idle": "2026-10-26T18:56:58.068161Z",
     "shell.execute_reply": "2026-10-26T18:56:58.067824Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "150.0\n",
      "Error: property 'balance' of 'BankAccount' object has no setter\n",
      "170.0\n"
     ]
    }
   ],
   "source": [
    "acct = BankAccount(\"Mia\", 150.0)\n",
    "# Access like an attribute, with no parentheses\n",
    "print(acct.balance)   # 150.0\n",
    "\n",
    "# Attempting to set it raises AttributeError (read-only)\n",
    "try:\n",
    "    acct.balance = 9999\n",
    "except AttributeError as e:\n",
    "    print(f\"Error: {e}\")\n",
    "\n",
    "# Use deposit and withdraw to change the balance\n",
    "acct.deposit(50.0)\n",
    "acct.withdraw(30.0)\n",
    "print(acct.balance)   # 170.0"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch09-property-boundary",
   "metadata": {},
   "source": [
    "The property blocks normal assignment such as `acct.balance = 9999`; it is not a security boundary. A caller can still access `_balance`, but doing so bypasses the interface and its invariant."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "id": "ch09-temp-props",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-26T18:56:58.069044Z",
     "iopub.status.busy": "2026-10-26T18:56:58.068980Z",
     "iopub.status.idle": "2026-10-26T18:56:58.070432Z",
     "shell.execute_reply": "2026-10-26T18:56:58.070137Z"
    },
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Properties\n",
    "#   Define a class Temperature that stores a reading in degrees Celsius.\n",
    "#   1. __init__(self, celsius=0.0) raises ValueError if celsius is below -273.15\n",
    "#      (absolute zero); otherwise it stores the value in _celsius.\n",
    "#   2. Add a read-only property celsius that returns _celsius.\n",
    "#   3. Add a read-only property fahrenheit that returns celsius * 9 / 5 + 32.\n",
    "#   4. Create t = Temperature(25) and print both properties.\n",
    "#   5. Try t.celsius = 30 and print the AttributeError message.\n",
    "#   6. Try Temperature(-300) and print the ValueError message.\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "### Your code ends here."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "id": "ch09-temp-props-sol",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-26T18:56:58.071354Z",
     "iopub.status.busy": "2026-10-26T18:56:58.071285Z",
     "iopub.status.idle": "2026-10-26T18:56:58.073454Z",
     "shell.execute_reply": "2026-10-26T18:56:58.073122Z"
    },
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "25 77.0\n",
      "property 'celsius' of 'Temperature' object has no setter\n",
      "Temperature cannot be below absolute zero\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "class Temperature:\n",
    "    def __init__(self, celsius=0.0):\n",
    "        if celsius < -273.15:\n",
    "            raise ValueError('Temperature cannot be below absolute zero')\n",
    "        self._celsius = celsius\n",
    "\n",
    "    @property\n",
    "    def celsius(self):\n",
    "        return self._celsius\n",
    "\n",
    "    @property\n",
    "    def fahrenheit(self):\n",
    "        return self._celsius * 9 / 5 + 32\n",
    "\n",
    "t = Temperature(25)\n",
    "print(t.celsius, t.fahrenheit)   # 25 77.0\n",
    "try:\n",
    "    t.celsius = 30\n",
    "except AttributeError as error:\n",
    "    print(error)\n",
    "try:\n",
    "    Temperature(-300)\n",
    "except ValueError as error:\n",
    "    print(error)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "00cc1003",
   "metadata": {},
   "source": [
    "### The `__str__` Method\n",
    "\n",
    "When you write a class, you can define a method named `__str__` to control\n",
    "how Python converts instances to a string.\n",
    "For example, here is the `__str__` method from the `BankAccount` class:\n",
    "\n",
    "```python\n",
    "    def __str__(self):\n",
    "        return f\"BankAccount(owner={self.owner}, balance=${self._balance:.2f})\"\n",
    "```\n",
    "\n",
    "This method returns a formatted string. You can invoke it directly:"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-00cc1003",
   "metadata": {},
   "source": [
    "```{index} string representation (__str__)\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "id": "f949934a",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-26T18:56:58.074327Z",
     "iopub.status.busy": "2026-10-26T18:56:58.074276Z",
     "iopub.status.idle": "2026-10-26T18:56:58.075990Z",
     "shell.execute_reply": "2026-10-26T18:56:58.075635Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'BankAccount(owner=Max, balance=$500.00)'"
      ]
     },
     "execution_count": 29,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "acct2 = BankAccount(\"Max\", 500.00)\n",
    "acct2.__str__()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4618a6a1",
   "metadata": {},
   "source": [
    "But Python can also invoke it for you.\n",
    "If you use the built-in function `str` to convert a `BankAccount` object to a string, Python uses the `__str__` method in the class."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "id": "ea9da0f1",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-26T18:56:58.076840Z",
     "iopub.status.busy": "2026-10-26T18:56:58.076758Z",
     "iopub.status.idle": "2026-10-26T18:56:58.078448Z",
     "shell.execute_reply": "2026-10-26T18:56:58.078094Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'BankAccount(owner=Max, balance=$500.00)'"
      ]
     },
     "execution_count": 30,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "str(acct2)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "00a8caca",
   "metadata": {},
   "source": [
    "And it does the same if you print a `BankAccount` object."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "id": "8dabd633",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-26T18:56:58.079374Z",
     "iopub.status.busy": "2026-10-26T18:56:58.079312Z",
     "iopub.status.idle": "2026-10-26T18:56:58.080809Z",
     "shell.execute_reply": "2026-10-26T18:56:58.080468Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "BankAccount(owner=Max, balance=$500.00)\n"
     ]
    }
   ],
   "source": [
    "print(acct2)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6efb95c7",
   "metadata": {},
   "source": [
    "Methods like `__str__` are called **special methods**, or **dunder methods** (short for \"double underscore\").\n",
    "You can identify them because their names begin and end with two underscores."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "dbc71922",
   "metadata": {},
   "source": [
    "### The `__repr__` Method\n",
    "\n",
    "`__repr__` returns a string that ideally looks like a valid Python expression\n",
    "that could recreate the object. It is used in the interactive interpreter and\n",
    "by `repr()`. When `__str__` is not defined, Python falls back to `__repr__`.\n",
    "\n",
    "| Method | Called by | Purpose |\n",
    "|---|---|---|\n",
    "| `__str__` | `str()`, `print()`, f-strings | Human-readable output |\n",
    "| `__repr__` | `repr()`, interactive shell | Unambiguous, ideally reconstructable |\n",
    "\n",
    "Here is the `__repr__` method from the `BankAccount` class:\n",
    "\n",
    "```python\n",
    "    def __repr__(self):\n",
    "        return f\"BankAccount({self.owner!r}, {self._balance!r})\"\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-dbc71922",
   "metadata": {},
   "source": [
    "```{index} object representation (__repr__), repr()\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "id": "ddabbc29",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-26T18:56:58.081722Z",
     "iopub.status.busy": "2026-10-26T18:56:58.081666Z",
     "iopub.status.idle": "2026-10-26T18:56:58.083152Z",
     "shell.execute_reply": "2026-10-26T18:56:58.082880Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "BankAccount(owner=Ava, balance=$945.30)\n",
      "BankAccount('Ava', 945.3)\n"
     ]
    }
   ],
   "source": [
    "acct = BankAccount(\"Ava\", 945.30)\n",
    "print(str(acct))    # BankAccount(owner=Ava, balance=$945.30)\n",
    "print(repr(acct))   # BankAccount('Ava', 945.3)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch09-repr-quoting",
   "metadata": {},
   "source": [
    "`!r` requests the representation of each inserted value. This preserves quotes and escapes inside names instead of manually surrounding a name with single quotes. Predict which quoting style appears for the next owner; either style is valid as long as it represents the string correctly."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "id": "ch09-repr-quoting-code",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-26T18:56:58.084036Z",
     "iopub.status.busy": "2026-10-26T18:56:58.083978Z",
     "iopub.status.idle": "2026-10-26T18:56:58.085303Z",
     "shell.execute_reply": "2026-10-26T18:56:58.085033Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "BankAccount(\"O'Neil\", 100)\n"
     ]
    }
   ],
   "source": [
    "quoted_owner = BankAccount(\"O'Neil\", 100)\n",
    "print(repr(quoted_owner))  # BankAccount(\"O'Neil\", 100)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "id": "ch09-temp-repr",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-26T18:56:58.086271Z",
     "iopub.status.busy": "2026-10-26T18:56:58.086202Z",
     "iopub.status.idle": "2026-10-26T18:56:58.087607Z",
     "shell.execute_reply": "2026-10-26T18:56:58.087327Z"
    },
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: String Representations\n",
    "#   Extend the Temperature class from the Properties practice.\n",
    "#   1. Add __str__ returning the reading with one decimal place, like \"25.0 C\".\n",
    "#   2. Add __repr__ returning text like \"Temperature(25)\"; use !r for the value.\n",
    "#   3. Create t = Temperature(25), then print str(t), repr(t), and t itself.\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "### Your code ends here."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "id": "ch09-temp-repr-sol",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-26T18:56:58.088502Z",
     "iopub.status.busy": "2026-10-26T18:56:58.088430Z",
     "iopub.status.idle": "2026-10-26T18:56:58.090856Z",
     "shell.execute_reply": "2026-10-26T18:56:58.090542Z"
    },
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "25.0 C\n",
      "Temperature(25)\n",
      "25.0 C\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "class Temperature:\n",
    "    def __init__(self, celsius=0.0):\n",
    "        if celsius < -273.15:\n",
    "            raise ValueError('Temperature cannot be below absolute zero')\n",
    "        self._celsius = celsius\n",
    "\n",
    "    @property\n",
    "    def celsius(self):\n",
    "        return self._celsius\n",
    "\n",
    "    @property\n",
    "    def fahrenheit(self):\n",
    "        return self._celsius * 9 / 5 + 32\n",
    "\n",
    "    def __str__(self):\n",
    "        return f'{self._celsius:.1f} C'\n",
    "\n",
    "    def __repr__(self):\n",
    "        return f'Temperature({self._celsius!r})'\n",
    "\n",
    "t = Temperature(25)\n",
    "print(str(t))    # 25.0 C\n",
    "print(repr(t))   # Temperature(25)\n",
    "print(t)         # 25.0 C"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch09-0901-exercises",
   "metadata": {},
   "source": [
    "## Exercises\n",
    "\n",
    "These tasks combine the class features from this section."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "id": "07c01dd6",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-26T18:56:58.091800Z",
     "iopub.status.busy": "2026-10-26T18:56:58.091746Z",
     "iopub.status.idle": "2026-10-26T18:56:58.093224Z",
     "shell.execute_reply": "2026-10-26T18:56:58.092890Z"
    },
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Independent Class Practice\n",
    "#   Build a new class without using `BankAccount`.\n",
    "#   1. Define a class `TaskList` whose `__init__` takes `owner`, stores it,\n",
    "#      and starts `tasks` as a new empty list.\n",
    "#   2. Add `add_task(task)` to append one task to the list.\n",
    "#   3. Add `task_count()` to return how many tasks are stored.\n",
    "#   4. Create t1 and t2 with different owners, add tasks to each.\n",
    "#   5. Add a read-only count property returning task_count().\n",
    "#   6. Add __str__ returning \"owner: N tasks\" and __repr__ using !r on owner and tasks.\n",
    "#   7. Print each owner with count, compare counts, and print str(t1) and repr(t1).\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "### Your code ends here."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "id": "e4e0d5a9",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-26T18:56:58.094122Z",
     "iopub.status.busy": "2026-10-26T18:56:58.094065Z",
     "iopub.status.idle": "2026-10-26T18:56:58.096537Z",
     "shell.execute_reply": "2026-10-26T18:56:58.096186Z"
    },
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Lia 2\n",
      "Noah 1\n",
      "True\n",
      "Lia: 2 tasks\n",
      "TaskList('Lia', ['Draft proposal', 'Email team'])\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "class TaskList:\n",
    "    def __init__(self, owner):\n",
    "        self.owner = owner\n",
    "        self.tasks = []\n",
    "\n",
    "    def add_task(self, task):\n",
    "        self.tasks.append(task)\n",
    "\n",
    "    def task_count(self):\n",
    "        return len(self.tasks)\n",
    "\n",
    "    @property\n",
    "    def count(self):\n",
    "        return self.task_count()\n",
    "\n",
    "    def __str__(self):\n",
    "        return f'{self.owner}: {self.count} tasks'\n",
    "\n",
    "    def __repr__(self):\n",
    "        return f'TaskList({self.owner!r}, {self.tasks!r})' \n",
    "\n",
    "t1 = TaskList(\"Lia\")\n",
    "t2 = TaskList(\"Noah\")\n",
    "t1.add_task(\"Draft proposal\")\n",
    "t1.add_task(\"Email team\")\n",
    "t2.add_task(\"Review notes\")\n",
    "\n",
    "print(t1.owner, t1.count)\n",
    "print(t2.owner, t2.count)\n",
    "print(t1.count > t2.count)\n",
    "print(str(t1))\n",
    "print(repr(t1))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "id": "3beb4e83",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-26T18:56:58.097408Z",
     "iopub.status.busy": "2026-10-26T18:56:58.097355Z",
     "iopub.status.idle": "2026-10-26T18:56:58.098741Z",
     "shell.execute_reply": "2026-10-26T18:56:58.098456Z"
    },
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Section Review\n",
    "#   1. Define a class `Wallet` with attributes `owner` and `cash`.\n",
    "#   2. Add a method `spend(amount)` that subtracts from `cash`. It raises\n",
    "#      `ValueError` if amount is not positive or is greater than available\n",
    "#      cash, before changing `cash`.\n",
    "#   3. Create `w = Wallet(\"Kai\", 40)` and call `w.spend(15)`.\n",
    "#   4. Print the remaining cash.\n",
    "#   5. Call `w.spend(-5)` inside try/except and print the error message.\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "id": "a18fd537",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-26T18:56:58.099554Z",
     "iopub.status.busy": "2026-10-26T18:56:58.099500Z",
     "iopub.status.idle": "2026-10-26T18:56:58.101361Z",
     "shell.execute_reply": "2026-10-26T18:56:58.101078Z"
    },
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "25\n",
      "Amount must be positive\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "class Wallet:\n",
    "    def __init__(self, owner, cash):\n",
    "        self.owner = owner\n",
    "        self.cash = cash\n",
    "\n",
    "    def spend(self, amount):\n",
    "        if amount <= 0:\n",
    "            raise ValueError(\"Amount must be positive\")\n",
    "        if amount > self.cash:\n",
    "            raise ValueError(\"Not enough cash\")\n",
    "        self.cash -= amount\n",
    "\n",
    "w = Wallet(\"Kai\", 40)\n",
    "w.spend(15)\n",
    "print(w.cash)   # 25\n",
    "try:\n",
    "    w.spend(-5)\n",
    "except ValueError as error:\n",
    "    print(error)   # Amount must be positive"
   ]
  }
 ],
 "metadata": {
  "celltoolbar": "Tags",
  "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.13"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
