{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "new-4c8a032b",
   "metadata": {},
   "source": [
    "# The Four Pillars of OOP"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "0f6e77dd",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2026-04-29T07:19:15.033699Z",
     "start_time": "2026-04-29T07:19:15.016769Z"
    },
    "execution": {
     "iopub.execute_input": "2026-10-26T19:35:32.434953Z",
     "iopub.status.busy": "2026-10-26T19:35:32.434673Z",
     "iopub.status.idle": "2026-10-26T19:35:33.000429Z",
     "shell.execute_reply": "2026-10-26T19:35:32.999954Z"
    },
    "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-pillars-route",
   "metadata": {},
   "source": [
    "Basic underscore conventions are part of the core reading because the examples use them. The detailed Name Mangling dropdown is optional."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "new-b65c5afe",
   "metadata": {},
   "source": [
    "Object-oriented programming is often organized around four big ideas known as the **four pillars of OOP**. These pillars are not strict rules that every class must follow in the same way. Instead, they are design principles that help you build programs that are easier to understand, extend, and maintain.\n",
    "\n",
    "When people say a program is \"object-oriented,\" they usually mean that classes and objects are used to organize related data together with the operations that act on that data. The four pillars give you a vocabulary for describing how that organization works.\n",
    "\n",
    "As you read each section, keep three questions in mind:\n",
    "\n",
    "- What problem does this pillar solve?\n",
    "- What does the Python code gain by using it?\n",
    "- What would the code look like without it?\n",
    "\n",
    "| Pillar | Core idea |\n",
    "|--------|-----------|\n",
    "| **Encapsulation** | Bundle data and behavior together, and protect internal state |\n",
    "| **Polymorphism** | Use a common interface even when different classes behave differently |\n",
    "| **Inheritance** | Build a new class by reusing and extending an existing one |\n",
    "| **Abstraction** | Show what an object can do without exposing every implementation detail |\n",
    "\n",
    "In practice, these ideas overlap. A class might use encapsulation to protect its data, inheritance to reuse behavior, polymorphism to work with many object types, and abstraction to present a simple public interface. This section treats them separately so each one is easier to see.\n",
    "\n",
    "Encapsulation comes first because it is one of the most immediate and practical ideas in everyday Python class design."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3767188f",
   "metadata": {},
   "source": [
    "The table below compares the four pillars side by side: what each one is for, what it focuses on, the design level where it works, and the Python tools that usually express it.\n",
    "\n",
    "| Aspect | Encapsulation | Polymorphism | Inheritance | Abstraction |\n",
    "|--------|---------------|--------------|-------------|-------------|\n",
    "| **Core Intent** | **Hide data/state.** Groups data and behavior, restricting direct outside access. | **Enable flexibility.** Allows a single interface or method name to handle multiple types. | **Reuse code.** Passes down properties and behaviors from an existing class to a new one. | **Hide complexity.** Shows only the essential features of a component. |\n",
    "| **Focus** | **How** an object protects its data integrity internally. | **Which** specific type or behavior a method takes during execution. | **Who** an object is in relation to others (the relationship hierarchy). | **What** an object does, rather than how it does it. |\n",
    "| **Design Level** | **Low-level implementation.** Restricting access and variables within the class code. | **Runtime/Execution.** Deciding which specific code execution path to take dynamically. | **Structural/Relational.** Organizing code into logical parent-child trees (`IS-A` relationships). | **High-level architectural/conceptual.** Defining the overall contract of software components. |\n",
    "| **Python Tools** | • Underscore names (`_balance`, `__salary`)<br>• `@property` for controlled access<br>• Methods that validate changes | • Method overriding<br>• Duck typing<br>• Special methods (`__str__`) | • `class Child(Parent):`<br>• `super()`<br>• Mixins | • Abstract base classes (`abc.ABC`, `@abstractmethod`)<br>• A small set of public methods |"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "contents",
   "metadata": {},
   "source": [
    "```{contents}\n",
    ":local:\n",
    ":depth: 2\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "new-462c4355",
   "metadata": {},
   "source": [
    "## Encapsulation"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-new-462c4355",
   "metadata": {},
   "source": [
    "```{index} encapsulation, public interface, getter\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cf7f2318",
   "metadata": {},
   "source": [
    "```{raw} html\n",
    "<div style=\"float: right; margin: 0 0 1rem 1.5rem; width: 252px; max-width: 100%;\">\n",
    "  <iframe width=\"252\" height=\"448\" style=\"max-width: 100%;\"\n",
    "    src=\"https://www.youtube-nocookie.com/embed/KZBX0NytylM\" title=\"Downsides of Python\"\n",
    "    frameborder=\"0\" allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture\"\n",
    "    allowfullscreen referrerpolicy=\"strict-origin-when-cross-origin\">\n",
    "  </iframe>\n",
    "  <p style=\"font-size: 0.85em; margin: 0.25rem 0 0;\"><em><a href=\"https://youtube.com/watch?v=KZBX0NytylM\">Downsides of Python (0:31)</a> by Ryan Peterman</em><br>Hosted on YouTube; property of its original creator, embedded here for educational reference only.</p>\n",
    "</div>\n",
    "```\n",
    "\n",
    "**Encapsulation** means that an object manages its own state (its data at a point in time) by keeping related data and behavior together and by controlling how that data is accessed or changed.\n",
    "\n",
    "This idea has two parts:\n",
    "\n",
    "- A class bundles attributes and methods into one coherent unit.\n",
    "- A class protects its internal state so values are changed in deliberate, valid ways rather than arbitrarily from outside the object.\n",
    "\n",
    "Encapsulation connects to several important ideas in software engineering:\n",
    "\n",
    "- **Bundling**: Grouping data and methods into one unit, the class.\n",
    "- **Information Hiding**: Restricting access to internal state. Python does this via convention and consensus. \n",
    "- **Abstraction**: the class can expose a simple public interface while hiding implementation details.\n",
    "- **Data integrity**: the class can validate updates and keep the object in a consistent state.\n",
    "\n",
    "In Python, encapsulation is based on conventions and interface design rather than strict access control such as the `private` keyword to block access as in Java. This is achieved by using **underscores** to signal intent to other developers: \n",
    "\n",
    "- `_variable` (**Internal by convention**): A single underscore tells other programmers, \"internal use by convention\", meaning \"This is internal; use it at your own risk because it might change.\" Python won't stop you from accessing it, but doing so is considered bad practice.\n",
    "- `__variable` (**Name-mangled**): A double underscore triggers **Name Mangling**. It reduces accidental name collisions with subclasses, but does not provide access security. The optional note below explains the rewritten spelling. \n",
    "\n",
    "The main goal of encapsulation is to make callers depend on the object's **public interface**, not on the details of how the object stores or computes its data.\n",
    "\n",
    "```{raw} html\n",
    "<div style=\"clear: both;\"></div>\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0b941422",
   "metadata": {},
   "source": [
    "Consider a payroll system. An employee's name is usually safe to expose directly, but salary updates need a controlled interface to keep values valid. Naming conventions and properties do not provide confidentiality. The example below stores the salary in a double-underscore attribute, exposes it through a read-only `@property`, and makes `give_raise()` the only way to change it."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b0d7bfd2",
   "metadata": {},
   "source": [
    ":::{admonition} @property == getter\n",
    ":class: dropdown\n",
    "If you have used Java or C#, you can think of `@property` as serving a role similar to a getter method. It lets callers access a value through a public interface while the class still controls how that value is computed or exposed.\n",
    "\n",
    "One important difference is syntax: in Python, a property is accessed like an attribute, so you write `emp.salary` rather than something like `emp.getSalary()`.\n",
    "\n",
    "The most common use of @property in practice is actually the read-only computed value pattern with no setter:\n",
    "\n",
    "```python\n",
    "@property\n",
    "def bmi(self):\n",
    "    return self.weight / (self.height ** 2)\n",
    "```\n",
    "\n",
    ":::"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "new-847d8503",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2026-04-29T07:19:15.059137Z",
     "start_time": "2026-04-29T07:19:15.040754Z"
    },
    "execution": {
     "iopub.execute_input": "2026-10-26T19:35:33.002245Z",
     "iopub.status.busy": "2026-10-26T19:35:33.002105Z",
     "iopub.status.idle": "2026-10-26T19:35:33.004743Z",
     "shell.execute_reply": "2026-10-26T19:35:33.004369Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Frederick\n",
      "50000\n",
      "55000.0\n",
      "Raise must be positive\n"
     ]
    }
   ],
   "source": [
    "class Employee:\n",
    "    def __init__(self, name, salary):\n",
    "        if salary < 0:              ### simple validation check salary is not negative\n",
    "            raise ValueError('Salary cannot be negative')\n",
    "\n",
    "        self.name = name            ### public attribute\n",
    "        self.__salary = salary      ### double underscore triggers name mangling; this is meant\n",
    "                                    ### for internal use and should not be accessed directly\n",
    "                                    ### from outside the class.\n",
    "\n",
    "    @property                       ### use property to expose salary through a controlled read-only interface.\n",
    "    def salary(self):               ###\n",
    "        return self.__salary\n",
    "\n",
    "    def give_raise(self, percent):  ### the one controlled way to change salary\n",
    "        if percent <= 0:\n",
    "            raise ValueError('Raise must be positive')\n",
    "        self.__salary = round(self.__salary * (1 + percent / 100), 2)\n",
    "        return self\n",
    "\n",
    "emp = Employee('Frederick', 50000)\n",
    "print(emp.name)\n",
    "print(emp.salary)   ### this calls the salary method, but you access it like an attribute (no parentheses)\n",
    "                    #   because of the @property decorator.\n",
    "\n",
    "emp.give_raise(10)\n",
    "print(emp.salary)   # 55000.0\n",
    "try:\n",
    "    emp.give_raise(-5)\n",
    "except ValueError as error:\n",
    "    print(error)    # Raise must be positive"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5b5248cf",
   "metadata": {},
   "source": [
    "The same encapsulation idea appears in banking systems. A bank account should not allow outside code to change the balance arbitrarily; instead, the class should expose controlled operations such as `deposit` and `withdraw`, along with a read-only way to inspect the current balance."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "3f8e20e0",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2026-04-29T07:19:15.077891Z",
     "start_time": "2026-04-29T07:19:15.061551Z"
    },
    "execution": {
     "iopub.execute_input": "2026-10-26T19:35:33.005817Z",
     "iopub.status.busy": "2026-10-26T19:35:33.005731Z",
     "iopub.status.idle": "2026-10-26T19:35:33.008310Z",
     "shell.execute_reply": "2026-10-26T19:35:33.007909Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "120\n"
     ]
    }
   ],
   "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",
    "acct = BankAccount('Alice', 100)\n",
    "acct.deposit(50)\n",
    "acct.withdraw(30)\n",
    "print(acct.balance)  # 120\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e11c6620",
   "metadata": {},
   "source": [
    "### Access Level Conventions\n",
    "\n",
    "Python does not enforce strict access modifiers like Java or C++. Instead, it uses naming patterns to communicate intent:\n",
    "\n",
    "- `name`: public\n",
    "- `_name`: internal use by convention\n",
    "- `__name`: triggers name mangling to reduce accidental access or accidental override in subclasses\n",
    "\n",
    "That last point matters: double underscore is more than a social convention. Python actually rewrites the attribute name internally. It is still not true private security, but it does provide stronger protection against accidental misuse than a single underscore.\n",
    "\n",
    "In the examples above:\n",
    "\n",
    "- `Employee.__salary` shows double-underscore name mangling.\n",
    "- `BankAccount._balance` shows an internal attribute exposed safely through methods and `@property`.\n",
    "\n",
    "See the note below for how name mangling works."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-e11c6620",
   "metadata": {},
   "source": [
    "```{index} name mangling, private attribute\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "09fb6061",
   "metadata": {
    "tags": [
     "optional-enrichment"
    ]
   },
   "source": [
    ":::{admonition} Name Mangling in Python\n",
    ":class: dropdown\n",
    "**Optional enrichment.** The required convention is that `__name` reduces accidental collisions, not that it provides security. Python rewrites `self.__salary` inside `Employee` to `_Employee__salary`. Knowing this rewritten spelling is not needed for the core examples.\n",
    "\n",
    "A single leading underscore is a convention for internal use; Python does not prevent direct access. Double underscores are chiefly useful when a base class needs to avoid accidental name collisions with subclasses.\n",
    ":::"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "p2-ex-enc-q",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-26T19:35:33.009419Z",
     "iopub.status.busy": "2026-10-26T19:35:33.009333Z",
     "iopub.status.idle": "2026-10-26T19:35:33.010848Z",
     "shell.execute_reply": "2026-10-26T19:35:33.010574Z"
    },
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Encapsulation\n",
    "#   1. Define a class Customer with a public attribute name and a\n",
    "#      name-mangled attribute __pin, both set in __init__.\n",
    "#   2. Add a read-only property masked_pin that returns '**' followed by\n",
    "#      the last two characters of the PIN.\n",
    "#   3. Add a method check_pin(pin) that returns True if pin matches __pin.\n",
    "#   4. Create c = Customer('Ava', '4821'). Print c.name, c.masked_pin,\n",
    "#      c.check_pin('0000'), and c.check_pin('4821').\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "### Your code ends here."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "p2-ex-enc-s",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-26T19:35:33.011867Z",
     "iopub.status.busy": "2026-10-26T19:35:33.011803Z",
     "iopub.status.idle": "2026-10-26T19:35:33.014061Z",
     "shell.execute_reply": "2026-10-26T19:35:33.013726Z"
    },
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Ava\n",
      "**21\n",
      "False\n",
      "True\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "class Customer:\n",
    "    def __init__(self, name, pin):\n",
    "        self.name = name\n",
    "        self.__pin = pin\n",
    "\n",
    "    @property\n",
    "    def masked_pin(self):\n",
    "        return '**' + self.__pin[-2:]\n",
    "\n",
    "    def check_pin(self, pin):\n",
    "        return pin == self.__pin\n",
    "\n",
    "c = Customer('Ava', '4821')\n",
    "print(c.name)\n",
    "print(c.masked_pin)\n",
    "print(c.check_pin('0000'))\n",
    "print(c.check_pin('4821'))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "227ff1ec",
   "metadata": {},
   "source": [
    "## Polymorphism\n",
    "\n",
    "**Polymorphism** means different object types can respond to the same method call in their own way.\n",
    "\n",
    "In the banking example below, each account type implements the same method, `month_end()`.\n",
    "The caller does not need `if/elif` logic for each account type; it calls one method name on all accounts."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-227ff1ec",
   "metadata": {},
   "source": [
    "```{index} polymorphism\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch09-polymorphism-version",
   "metadata": {},
   "source": [
    "The next three classes do not share a parent class, and they are not the `BankAccount` class from above. Each one stores a public `balance` and provides its own `month_end()` method."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "3a940b86",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2026-04-29T07:19:15.089093Z",
     "start_time": "2026-04-29T07:19:15.079822Z"
    },
    "execution": {
     "iopub.execute_input": "2026-10-26T19:35:33.015086Z",
     "iopub.status.busy": "2026-10-26T19:35:33.015022Z",
     "iopub.status.idle": "2026-10-26T19:35:33.017292Z",
     "shell.execute_reply": "2026-10-26T19:35:33.016947Z"
    }
   },
   "outputs": [],
   "source": [
    "class CheckingAccount:\n",
    "    def __init__(self, owner, balance):\n",
    "        self.owner = owner\n",
    "        self.balance = balance\n",
    "\n",
    "    def month_end(self):\n",
    "        self.balance -= 10   # monthly service fee\n",
    "\n",
    "\n",
    "class InterestAccount:\n",
    "    def __init__(self, owner, balance, rate=0.01):\n",
    "        self.owner = owner\n",
    "        self.balance = balance\n",
    "        self.rate = rate\n",
    "\n",
    "    def month_end(self):\n",
    "        self.balance += self.balance * self.rate   # monthly interest\n",
    "\n",
    "\n",
    "class LoanAccount:\n",
    "    def __init__(self, owner, balance, rate=0.015):\n",
    "        self.owner = owner\n",
    "        self.balance = balance\n",
    "        self.rate = rate\n",
    "\n",
    "    def month_end(self):\n",
    "        self.balance += self.balance * self.rate   # interest on amount owed\n",
    "\n",
    "\n",
    "accounts = [                        ### a list of different account types\n",
    "    CheckingAccount('Alice', 1200), ### each one can run month_end(), whatever its class\n",
    "    InterestAccount('Bob', 5000),\n",
    "    LoanAccount('Charlie', 2000),\n",
    "]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "771862a7",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2026-04-29T07:19:15.097092Z",
     "start_time": "2026-04-29T07:19:15.089593Z"
    },
    "execution": {
     "iopub.execute_input": "2026-10-26T19:35:33.018309Z",
     "iopub.status.busy": "2026-10-26T19:35:33.018253Z",
     "iopub.status.idle": "2026-10-26T19:35:33.019896Z",
     "shell.execute_reply": "2026-10-26T19:35:33.019515Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Before month-end:\n",
      "Alice: 1200.00\n",
      "Bob: 5000.00\n",
      "Charlie: 2000.00\n"
     ]
    }
   ],
   "source": [
    "print('Before month-end:')\n",
    "for account in accounts:\n",
    "    print(f'{account.owner}: {account.balance:.2f}')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c7e155bb",
   "metadata": {},
   "source": [
    "All objects in `accounts` provide `month_end()`, so one uniform loop can apply month-end updates .\n",
    "No type-specific `if/elif` branches are needed."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "62ae4907",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2026-04-29T07:19:15.107462Z",
     "start_time": "2026-04-29T07:19:15.101426Z"
    },
    "execution": {
     "iopub.execute_input": "2026-10-26T19:35:33.020766Z",
     "iopub.status.busy": "2026-10-26T19:35:33.020704Z",
     "iopub.status.idle": "2026-10-26T19:35:33.022247Z",
     "shell.execute_reply": "2026-10-26T19:35:33.021962Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "After month-end:\n",
      "Alice: 1190.00\n",
      "Bob: 5050.00\n",
      "Charlie: 2030.00\n"
     ]
    }
   ],
   "source": [
    "for account in accounts:\n",
    "    account.month_end()   # polymorphic call\n",
    "\n",
    "print('\\nAfter month-end:')\n",
    "for account in accounts:\n",
    "    print(f'{account.owner}: {account.balance:.2f}')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "69c8440f",
   "metadata": {},
   "source": [
    "In this loop, `account` can be a `CheckingAccount`, `InterestAccount`, or `LoanAccount`,\n",
    "but the caller code is identical:\n",
    "\n",
    "`account.month_end()`\n",
    "\n",
    "Python dispatches to the correct **class-specific** implementation at runtime.\n",
    "That is the core idea of **polymorphism**: one interface, many behaviors.\n",
    "\n",
    "The three classes share no parent class. The loop works only because each object has a `month_end()` method. Python checks for the method when the call happens, not for the object's type. This style is called **duck typing**: if an object can do what the code asks, its class does not matter. Inheritance and abstract base classes, later in this section, make a shared interface explicit, but Python polymorphism does not require them."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-ch09-duck-typing",
   "metadata": {},
   "source": [
    "```{index} duck typing\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "74ee140005db2bee",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2026-04-29T07:19:15.118090Z",
     "start_time": "2026-04-29T07:19:15.113884Z"
    },
    "execution": {
     "iopub.execute_input": "2026-10-26T19:35:33.023339Z",
     "iopub.status.busy": "2026-10-26T19:35:33.023271Z",
     "iopub.status.idle": "2026-10-26T19:35:33.024753Z",
     "shell.execute_reply": "2026-10-26T19:35:33.024458Z"
    },
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Banking Polymorphism\n",
    "#   The classes CheckingAccount, InterestAccount, and LoanAccount are already defined above.\n",
    "#\n",
    "#   1. Define a new class InvestmentAccount with:\n",
    "#         - __init__(self, owner, balance, rate=0.02)\n",
    "#         - month_end(self) that first adds interest at self.rate and then\n",
    "#           subtracts a $5 management fee\n",
    "#\n",
    "#   2. Create one instance of each of the four account types:\n",
    "#         CheckingAccount('Alice', 1200)\n",
    "#         InterestAccount('Bob', 5000)\n",
    "#         LoanAccount('Charlie', 2000)\n",
    "#         InvestmentAccount('Diana', 3000, 0.02)\n",
    "#\n",
    "#   3. Put all four in a list called accounts.\n",
    "#   4. Loop over accounts and call month_end() on each one.\n",
    "#   5. Loop again and print each owner's updated balance.\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "b236ea9676058ea8",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2026-04-29T07:19:15.122902Z",
     "start_time": "2026-04-29T07:19:15.118349Z"
    },
    "execution": {
     "iopub.execute_input": "2026-10-26T19:35:33.025656Z",
     "iopub.status.busy": "2026-10-26T19:35:33.025589Z",
     "iopub.status.idle": "2026-10-26T19:35:33.027859Z",
     "shell.execute_reply": "2026-10-26T19:35:33.027478Z"
    },
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Alice: 1190.00\n",
      "Bob: 5050.00\n",
      "Charlie: 2030.00\n",
      "Diana: 3055.00\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "class InvestmentAccount:\n",
    "    def __init__(self, owner, balance, rate=0.02):\n",
    "        self.owner = owner\n",
    "        self.balance = balance\n",
    "        self.rate = rate\n",
    "\n",
    "    def month_end(self):\n",
    "        self.balance += self.balance * self.rate   # interest first\n",
    "        self.balance -= 5                          # then the management fee\n",
    "\n",
    "accounts = [\n",
    "    CheckingAccount('Alice', 1200),\n",
    "    InterestAccount('Bob', 5000),\n",
    "    LoanAccount('Charlie', 2000),\n",
    "    InvestmentAccount('Diana', 3000, 0.02),\n",
    "]\n",
    "\n",
    "for account in accounts:\n",
    "    account.month_end()\n",
    "\n",
    "for account in accounts:\n",
    "    print(f'{account.owner}: {account.balance:.2f}')\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ced31782",
   "metadata": {
    "tags": []
   },
   "source": [
    "## Inheritance\n",
    "\n",
    "The language feature most often associated with object-oriented programming is **inheritance**. Inheritance lets you define a new class as a modified or specialized version of an existing class.\n",
    "\n",
    "When inheritance is used well, it helps you avoid rewriting code that is already correct in the parent class. The child class reuses what it needs and adds or overrides only the parts that make it different.\n",
    "\n",
    "The examples in this section use bank accounts. That domain is close to the kinds of systems used in business settings, but the main idea is general: _**a child class can reuse behavior from a parent class and then extend it for a more specific purpose**_."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-ced31782",
   "metadata": {},
   "source": [
    "```{index} inheritance, subclass, superclass\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "4232fb35",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2026-04-29T07:19:15.150900Z",
     "start_time": "2026-04-29T07:19:15.127311Z"
    },
    "execution": {
     "iopub.execute_input": "2026-10-26T19:35:33.028880Z",
     "iopub.status.busy": "2026-10-26T19:35:33.028817Z",
     "iopub.status.idle": "2026-10-26T19:35:33.031342Z",
     "shell.execute_reply": "2026-10-26T19:35:33.031043Z"
    }
   },
   "outputs": [],
   "source": [
    "class BankAccount:\n",
    "    \"\"\"A teaching account with controlled balance updates.\"\"\"\n",
    "\n",
    "    def __init__(self, account_number, owner, balance=0.0):\n",
    "        if balance < 0:\n",
    "            raise ValueError('Starting balance cannot be negative')\n",
    "        self.account_number = account_number\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'{self.account_number}: {self.owner} - ${self.balance:.2f}'\n",
    "\n",
    "    def transfer_to(self, other_account, amount):\n",
    "        if not isinstance(other_account, BankAccount):\n",
    "            raise TypeError('Transfers require another BankAccount')\n",
    "        self.withdraw(amount)\n",
    "        other_account.deposit(amount)\n",
    "        return self\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bd9ee184",
   "metadata": {},
   "source": [
    "A subclass is defined with the same `class` statement as any other class. The difference is that the parent class name appears in parentheses after the subclass name."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch09-inheritance-version",
   "metadata": {},
   "source": [
    "The examples in this section use a new version of `BankAccount` whose constructor takes an `account_number` before the `owner`. It keeps the same rules as before: a nonnegative starting balance, a read-only public `balance`, positive update amounts, and `deposit()` and `withdraw()` returning the account.\n",
    "\n",
    "Use inheritance when the child should support the parent's public operations. A subclass can add a rate or a withdrawal rule while keeping callers' expectations about balance access and update results. Redefining a class with the same name replaces it for newly created objects; it does not change objects created earlier."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0502961b",
   "metadata": {},
   "source": [
    "### Parents and children\n",
    "\n",
    "Inheritance is the ability to define a new class that is a modified version of an existing class.\n",
    "A useful banking example is a `SavingsAccount`, which is a specific kind of `BankAccount`.\n",
    "\n",
    "* A savings account is similar to a general bank account because it still has an owner, an account number, a balance, and common operations such as deposit and withdrawal, which you can reuse instead of defining them again.\n",
    "\n",
    "* A savings account is also different because it has behavior that does not apply to every account type. For example, it earns interest at its own rate. The version below stores that rate in the child class; a method that uses it would be added the same way `BusinessAccount` adds `withdraw_with_fee()` later in this section.\n",
    "\n",
    "This relationship between classes, where one is a **specialized** version of another, lends itself naturally to inheritance. To define a new class that is based on an existing class, the name of the existing class is placed in parentheses.\n",
    "\n",
    "The basic pattern for Python syntax for inheritance is:\n",
    "\n",
    "```python\n",
    "class Parent:\n",
    "    def __init__(self, x):\n",
    "        self.x = x\n",
    "\n",
    "class Child(Parent):\n",
    "    def __init__(self, x, y):\n",
    "        super().__init__(x)   # call Parent.__init__\n",
    "        self.y = y\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-0502961b",
   "metadata": {},
   "source": [
    "```{index} parent class, child class, super()\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "71c06d43",
   "metadata": {},
   "source": [
    ":::{admonition} `super()`\n",
    ":class: dropdown\n",
    "`super()` returns a proxy object that makes it possible to call a method from a parent class without naming that parent explicitly. This is especially useful in `__init__`, where the child class often relies on the parent class to set up shared state before adding child-specific attributes.\n",
    "\n",
    "Example in constructors:\n",
    "\n",
    "```python\n",
    "class Animal:\n",
    "    def __init__(self, name, sound):\n",
    "        self.name = name\n",
    "        self.sound = sound\n",
    "\n",
    "    def speak(self):\n",
    "        return f'{self.name} says {self.sound}!'\n",
    "\n",
    "class Dog(Animal):\n",
    "    def __init__(self, name, breed):\n",
    "        super().__init__(name, sound='Woof')  # call parent __init__ first\n",
    "        self.breed = breed                    # then add child-specific data\n",
    "\n",
    "    def info(self):\n",
    "        return f'{self.name} is a {self.breed}'\n",
    "\n",
    "d = Dog('Rex', 'Labrador')\n",
    "print(d.speak())   # inherited behavior uses parent setup\n",
    "print(d.info())    # child-specific behavior\n",
    "```\n",
    "\n",
    "There is also a pattern for **methods overriding**:\n",
    "\n",
    "```python\n",
    "class Parent:\n",
    "    def greet(self):\n",
    "        return \"Hello\"\n",
    "\n",
    "class Child(Parent):            ### inheritance \n",
    "    def greet(self):            ### same method\n",
    "        return super().greet() + \", from Child\"\n",
    "```\n",
    ":::\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "61923c48",
   "metadata": {},
   "source": [
    "In this pattern, `Child` is the subclass and `Parent` is the superclass. To create an inheritance relation for the example below (`BankAccount` is the `parent` class and `SavingsAccount` is the `child` class), \n",
    "\n",
    "```python\n",
    "class SavingsAccount(BankAccount):\n",
    "    pass                        ### no code needed but can't leave it blank\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "965ddccd",
   "metadata": {},
   "source": [
    "The next cell defines `SavingsAccount` as a child class of `BankAccount`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "f39fc598",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2026-04-29T07:19:15.160174Z",
     "start_time": "2026-04-29T07:19:15.155314Z"
    },
    "execution": {
     "iopub.execute_input": "2026-10-26T19:35:33.032551Z",
     "iopub.status.busy": "2026-10-26T19:35:33.032489Z",
     "iopub.status.idle": "2026-10-26T19:35:33.034179Z",
     "shell.execute_reply": "2026-10-26T19:35:33.033797Z"
    }
   },
   "outputs": [],
   "source": [
    "class SavingsAccount(BankAccount):\n",
    "    \"\"\"Represents a savings account.\"\"\"\n",
    "\n",
    "    def __init__(self, account_number, owner, balance=0.0, rate=0.01):\n",
    "        super().__init__(account_number, owner, balance)    ### # call Parent.__init__ to initialize the common attributes\n",
    "        self.rate = rate    ### extra attribute specific to SavingsAccount"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "339295cd",
   "metadata": {},
   "source": [
    "This definition indicates that `SavingsAccount` inherits from `BankAccount`, which means that `SavingsAccount` objects can access methods defined in `BankAccount`, like `deposit` and `withdraw`.\n",
    "\n",
    "`SavingsAccount` also inherits `__init__` from `BankAccount`, but if you define `__init__` in the `SavingsAccount` class, it overrides the one in the `BankAccount` class.\n",
    "\n",
    "Note that:\n",
    "\n",
    "- `SavingsAccount` is a subclass of `BankAccount` because `BankAccount` is in parentheses of the header of `SavingsAccount`.\n",
    "- there is a `__init__` constructor here and it has all the parameters the parent class has and an additional parameter `rate=`.\n",
    "- `super().__init__(...)` reuses the parent initializer to set up the account number, owner, and balance.\n",
    "- the child then initializes its specialized attribute: `rate`, which does not exist in the parent class.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9b6a763a",
   "metadata": {},
   "source": [
    "This version of `__init__` takes the same basic account information as the parent class and adds an interest rate.\n",
    "When a `SavingsAccount` is created, Python invokes this method, but `super().__init__(...)` reuses the parent setup so the shared attributes do not have to be written again."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "8de8cff4",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2026-04-29T07:19:15.169531Z",
     "start_time": "2026-04-29T07:19:15.161222Z"
    },
    "execution": {
     "iopub.execute_input": "2026-10-26T19:35:33.035114Z",
     "iopub.status.busy": "2026-10-26T19:35:33.035058Z",
     "iopub.status.idle": "2026-10-26T19:35:33.036564Z",
     "shell.execute_reply": "2026-10-26T19:35:33.036268Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.02\n"
     ]
    }
   ],
   "source": [
    "savings = SavingsAccount('S-1001', 'Ava', 1200.00, rate=0.02)\n",
    "print(savings.rate)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b1e2a67d",
   "metadata": {},
   "source": [
    "Because `SavingsAccount` inherits from `BankAccount`, it can use methods defined in the parent class without redefining them. The next example calls `deposit` method, which was written once in `BankAccount` and then reused by the child class."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "9f582ce0",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2026-04-29T07:19:15.182801Z",
     "start_time": "2026-04-29T07:19:15.171099Z"
    },
    "execution": {
     "iopub.execute_input": "2026-10-26T19:35:33.037557Z",
     "iopub.status.busy": "2026-10-26T19:35:33.037490Z",
     "iopub.status.idle": "2026-10-26T19:35:33.038997Z",
     "shell.execute_reply": "2026-10-26T19:35:33.038743Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "S-1001: Ava - $1500.00\n",
      "True\n",
      "True\n"
     ]
    }
   ],
   "source": [
    "savings.deposit(300.00)                 ### inherited method from BankAccount\n",
    "print(savings)\n",
    "print(isinstance(savings, SavingsAccount))\n",
    "print(isinstance(savings, BankAccount))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "dc2ce06b",
   "metadata": {},
   "source": [
    "The parent class also defines a method that is shared by every kind of bank account. A transfer operation belongs in the parent class because it is useful for a regular bank account, a savings account, and any future subclass that behaves like a bank account."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch09-transfer-snippet",
   "metadata": {},
   "source": [
    "```python\n",
    "    def transfer_to(self, other_account, amount):\n",
    "        if not isinstance(other_account, BankAccount):\n",
    "            raise TypeError('Transfers require another BankAccount')\n",
    "        self.withdraw(amount)\n",
    "        other_account.deposit(amount)\n",
    "        return self\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "16e6c404",
   "metadata": {},
   "source": [
    "This method is defined once in the parent class, but it can be used by any child class that inherits from `BankAccount`. That is one of the main advantages of inheritance: common behavior lives in one place instead of being duplicated across several related classes."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e648a722",
   "metadata": {},
   "source": [
    "A child class is often called a ***subclass***, and the parent class is often called a ***superclass***. In this example, `SavingsAccount` is a subclass of `BankAccount`, and `BankAccount` is a superclass of `SavingsAccount`.\n",
    "\n",
    "A `SavingsAccount` should be usable anywhere a `BankAccount` is expected because it still supports the same core account behaviors. That idea makes inheritance practical: the parent class defines what related objects have in common, and the child class adds what makes it special."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e80873dd",
   "metadata": {},
   "source": [
    "### Specialization\n",
    "\n",
    "Inheritance becomes especially useful when subclasses need to keep the basic behavior of the parent class but also add rules of their own.\n",
    "A `BusinessAccount`, for example, is still a bank account, but it may charge a service fee for certain withdrawals. That makes it a good example of specialization."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-e80873dd",
   "metadata": {},
   "source": [
    "```{index} specialization\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "b9e949cf",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2026-04-29T07:19:15.188434Z",
     "start_time": "2026-04-29T07:19:15.184329Z"
    },
    "execution": {
     "iopub.execute_input": "2026-10-26T19:35:33.040205Z",
     "iopub.status.busy": "2026-10-26T19:35:33.040150Z",
     "iopub.status.idle": "2026-10-26T19:35:33.042014Z",
     "shell.execute_reply": "2026-10-26T19:35:33.041653Z"
    }
   },
   "outputs": [],
   "source": [
    "class BusinessAccount(BankAccount):\n",
    "    \"\"\"Represents a business checking account.\"\"\"\n",
    "\n",
    "    def __init__(self, account_number, owner, balance=0.0, transaction_fee=5.0):\n",
    "        super().__init__(account_number, owner, balance)\n",
    "        if transaction_fee < 0:\n",
    "            raise ValueError('Transaction fee cannot be negative')\n",
    "        self.transaction_fee = transaction_fee\n",
    "\n",
    "    def withdraw_with_fee(self, amount):\n",
    "        if amount <= 0:\n",
    "            raise ValueError('Withdrawal must be positive')\n",
    "        total = amount + self.transaction_fee\n",
    "        self.withdraw(total)\n",
    "        return total"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4c038717",
   "metadata": {},
   "source": [
    "The `withdraw_with_fee` method deducts both the requested withdrawal amount and the transaction fee from the account balance."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "0586b764",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2026-04-29T07:19:15.198012Z",
     "start_time": "2026-04-29T07:19:15.189219Z"
    },
    "execution": {
     "iopub.execute_input": "2026-10-26T19:35:33.042962Z",
     "iopub.status.busy": "2026-10-26T19:35:33.042902Z",
     "iopub.status.idle": "2026-10-26T19:35:33.044582Z",
     "shell.execute_reply": "2026-10-26T19:35:33.044205Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Withdrawn: $200.00, Fee: $5.00, Total deducted: $205.00\n",
      "B-1001: Acme Corp - $795.00\n"
     ]
    }
   ],
   "source": [
    "biz = BusinessAccount('B-1001', 'Acme Corp', 1000.0)    ### 1000 in initial balance\n",
    "total = biz.withdraw_with_fee(200)\n",
    "print(f'Withdrawn: $200.00, Fee: ${biz.transaction_fee:.2f}, Total deducted: ${total:.2f}')\n",
    "print(biz)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c3a7820d",
   "metadata": {},
   "source": [
    "The `withdraw_with_fee` method belongs in the child class because the extra fee is specific to business accounts, not to every kind of bank account."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ea7cb85216c27c29",
   "metadata": {},
   "source": [
    "On the other hand, the `transfer_to()` method is in the superclass so that the subclasses can use them."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "227bef61",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2026-04-29T07:19:15.207678Z",
     "start_time": "2026-04-29T07:19:15.199368Z"
    },
    "execution": {
     "iopub.execute_input": "2026-10-26T19:35:33.045612Z",
     "iopub.status.busy": "2026-10-26T19:35:33.045544Z",
     "iopub.status.idle": "2026-10-26T19:35:33.047191Z",
     "shell.execute_reply": "2026-10-26T19:35:33.046865Z"
    },
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "B-2001: Northwind Supply - $4600.00\n",
      "S-2002: Mina - $2200.00\n"
     ]
    }
   ],
   "source": [
    "business = BusinessAccount('B-2001', 'Northwind Supply', 5000.00, transaction_fee=12.50)\n",
    "personal = SavingsAccount('S-2002', 'Mina', 1800.00, rate=0.03)\n",
    "\n",
    "business.transfer_to(personal, 400.00)\n",
    "print(business)\n",
    "print(personal)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1933ca904c358746",
   "metadata": {},
   "source": [
    "The same `business` account can also make a fee-based withdrawal. `withdraw_with_fee()` takes only the amount; the fee comes from the account itself, which was created with `transaction_fee=12.50`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "f7d9275a",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2026-04-29T07:19:15.219965Z",
     "start_time": "2026-04-29T07:19:15.211858Z"
    },
    "execution": {
     "iopub.execute_input": "2026-10-26T19:35:33.048058Z",
     "iopub.status.busy": "2026-10-26T19:35:33.047993Z",
     "iopub.status.idle": "2026-10-26T19:35:33.049484Z",
     "shell.execute_reply": "2026-10-26T19:35:33.049179Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Total charged: $262.50\n",
      "B-2001: Northwind Supply - $4337.50\n"
     ]
    }
   ],
   "source": [
    "charged = business.withdraw_with_fee(250.00)\n",
    "print(f'Total charged: ${charged:.2f}')\n",
    "print(business)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a1bd2521",
   "metadata": {},
   "source": [
    "`withdraw_with_fee` subtracts both the withdrawal amount and the fee, while the inherited methods from `BankAccount` still handle the core balance updates."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "ceb63a74",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2026-04-29T07:19:15.232319Z",
     "start_time": "2026-04-29T07:19:15.221093Z"
    },
    "execution": {
     "iopub.execute_input": "2026-10-26T19:35:33.050452Z",
     "iopub.status.busy": "2026-10-26T19:35:33.050401Z",
     "iopub.status.idle": "2026-10-26T19:35:33.052867Z",
     "shell.execute_reply": "2026-10-26T19:35:33.052546Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "4337.5"
      ]
     },
     "execution_count": 19,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "business.balance"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b4f5e107",
   "metadata": {},
   "source": [
    "In this example, `BusinessAccount` inherited general account behavior from `BankAccount` and then added specialized behavior of its own. The **child class did not need to rewrite** deposit, basic withdrawal, string display, or transfer logic."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "eeb70a14",
   "metadata": {},
   "source": [
    "The `SavingsAccount` and `BusinessAccount` classes inherited all the methods from `BankAccount`, such as `deposit`, `withdraw`, `__str__`, and `transfer_to`, but each subclass also gained attributes or methods that reflect its own role in the banking system."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d2f48aae",
   "metadata": {},
   "source": [
    "### `issubclass()`\n",
    "\n",
    "The `issubclass()` checks whether one class inherits from another at runtime."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-d2f48aae",
   "metadata": {},
   "source": [
    "```{index} issubclass()\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a2eae40e",
   "metadata": {},
   "source": [
    "`issubclass(Child, Parent)` returns `True` if `Child` is a subclass of `Parent` or is `Parent` itself. It is useful when class relationships need to be checked at runtime.\n",
    "\n",
    "A practical detail matters here: the first argument to `issubclass()` must itself be a class. If user input or function arguments are being validated, that point is often worth checking explicitly before calling `issubclass()`.\n",
    "\n",
    "| Function | Checks |\n",
    "|---|---|\n",
    "| `isinstance(obj, cls)` | Is `obj` an instance of `cls` or one of its subclasses? |\n",
    "| `issubclass(A, B)` | Is class `A` a subclass of `B`? |\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "ae99919c",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2026-04-29T07:19:15.239512Z",
     "start_time": "2026-04-29T07:19:15.233834Z"
    },
    "execution": {
     "iopub.execute_input": "2026-10-26T19:35:33.053871Z",
     "iopub.status.busy": "2026-10-26T19:35:33.053820Z",
     "iopub.status.idle": "2026-10-26T19:35:33.055727Z",
     "shell.execute_reply": "2026-10-26T19:35:33.055432Z"
    }
   },
   "outputs": [],
   "source": [
    "class Animal:\n",
    "    def __init__(self, name, sound):\n",
    "        self.name = name\n",
    "        self.sound = sound\n",
    "\n",
    "    def speak(self):\n",
    "        return f'{self.name} says {self.sound}!'\n",
    "\n",
    "class Dog(Animal):\n",
    "    def __init__(self, name, breed):\n",
    "        super().__init__(name, sound='Woof')\n",
    "        self.breed = breed\n",
    "\n",
    "    def info(self):\n",
    "        return f'{self.name} is a {self.breed}'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "39215215",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2026-04-29T07:19:15.252912Z",
     "start_time": "2026-04-29T07:19:15.240991Z"
    },
    "execution": {
     "iopub.execute_input": "2026-10-26T19:35:33.056534Z",
     "iopub.status.busy": "2026-10-26T19:35:33.056473Z",
     "iopub.status.idle": "2026-10-26T19:35:33.058310Z",
     "shell.execute_reply": "2026-10-26T19:35:33.058022Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "True\n",
      "False\n",
      "True\n",
      "Rex says Woof!\n"
     ]
    }
   ],
   "source": [
    "\n",
    "print(issubclass(Dog, Animal))   # True\n",
    "print(issubclass(Animal, Dog))   # False\n",
    "print(issubclass(Dog, Dog))      # True (a class is a subclass of itself)\n",
    "\n",
    "# Common use: guarding against wrong arguments\n",
    "def make_animal(cls, *args, **kwargs):\n",
    "    if not isinstance(cls, type):\n",
    "        raise TypeError('cls must be a class')\n",
    "    if not issubclass(cls, Animal):\n",
    "        raise TypeError(f'{cls} is not an Animal subclass')\n",
    "    return cls(*args, **kwargs)\n",
    "\n",
    "rex = make_animal(Dog, 'Rex', 'Labrador')\n",
    "print(rex.speak())   # Rex says Woof!"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bcadecf3",
   "metadata": {},
   "source": [
    "### Class Variables\n",
    "\n",
    "A class can also store values in its class body, such as a bank name or a default transfer fee. Every instance shares these **class variables**, and every subclass inherits them:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ch09-0902-classvar-code",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Animalia\n",
      "Animalia\n"
     ]
    }
   ],
   "source": [
    "class Animal:\n",
    "    kingdom = 'Animalia'      # class variable, shared by every Animal\n",
    "\n",
    "class Dog(Animal):\n",
    "    pass\n",
    "\n",
    "print(Dog.kingdom)       # inherited from Animal\n",
    "print(Dog().kingdom)     # an instance sees it too"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch09-0902-classvar-link",
   "metadata": {},
   "source": [
    "{doc}`Advanced OOP <0903-oop-advanced>` covers class variables in full, including what happens when an instance assigns to one."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "33de8e90",
   "metadata": {},
   "source": [
    "### Method Overriding\n",
    "\n",
    "An **override** happens when a child class defines a method with the **same name** as a parent method to change or specialize behavior.\n",
    "\n",
    "A common pattern is:\n",
    "\n",
    "- add child-specific validation or rules\n",
    "- then call `super().method(...)` to reuse the parent logic\n",
    "\n",
    "This keeps shared behavior in one place while still allowing specialization."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-33de8e90",
   "metadata": {},
   "source": [
    "```{index} method overriding\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "id": "e040971b",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-26T19:35:33.059356Z",
     "iopub.status.busy": "2026-10-26T19:35:33.059295Z",
     "iopub.status.idle": "2026-10-26T19:35:33.061541Z",
     "shell.execute_reply": "2026-10-26T19:35:33.061152Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "S-9001: Nina - $250.00\n",
      "Cannot go below minimum balance of $200.00\n"
     ]
    }
   ],
   "source": [
    "class LimitedSavingsAccount(SavingsAccount):\n",
    "    def __init__(self, account_number, owner, balance=0.0, rate=0.01, min_balance=100.0):\n",
    "        super().__init__(account_number, owner, balance, rate)\n",
    "        self.min_balance = min_balance\n",
    "\n",
    "    def withdraw(self, amount):\n",
    "        # Child-specific rule before parent logic\n",
    "        if self.balance - amount < self.min_balance:\n",
    "            raise ValueError(f'Cannot go below minimum balance of ${self.min_balance:.2f}')\n",
    "        return super().withdraw(amount)  # preserve the parent return contract\n",
    "\n",
    "lsa = LimitedSavingsAccount('S-9001', 'Nina', 500.0, rate=0.02, min_balance=200.0)\n",
    "lsa.withdraw(250)\n",
    "print(lsa)\n",
    "\n",
    "try:\n",
    "    lsa.withdraw(100)\n",
    "except ValueError as e:\n",
    "    print(e)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch09-override-feedback",
   "metadata": {},
   "source": [
    "The child checks its minimum-balance rule, then delegates to the parent's positive-amount and funds checks. Neither version subtracts before validating. Returning the parent's result preserves the `withdraw()` contract, so inherited callers need not change how they use a successful update."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "p2-ex-inh-q",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-26T19:35:33.062512Z",
     "iopub.status.busy": "2026-10-26T19:35:33.062456Z",
     "iopub.status.idle": "2026-10-26T19:35:33.063882Z",
     "shell.execute_reply": "2026-10-26T19:35:33.063598Z"
    },
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Inheritance\n",
    "#   1. Define a parent class Account with owner and balance in __init__,\n",
    "#      a withdraw(amount) method that raises ValueError('Insufficient funds')\n",
    "#      if amount > balance, and a __str__ that returns 'owner: $balance'.\n",
    "#   2. Define a child class StudentAccount(Account) that:\n",
    "#         - adds a school attribute, using super().__init__() for the rest\n",
    "#         - overrides withdraw(amount) to raise ValueError if amount > 200,\n",
    "#           then calls super().withdraw(amount)\n",
    "#   3. Create s = StudentAccount('Leo', 500, 'State U') and call s.withdraw(150).\n",
    "#   4. Print s, then try s.withdraw(250) and print the error message.\n",
    "#   5. Print isinstance(s, Account) and issubclass(StudentAccount, Account).\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "### Your code ends here."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "id": "p2-ex-inh-s",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-26T19:35:33.064724Z",
     "iopub.status.busy": "2026-10-26T19:35:33.064661Z",
     "iopub.status.idle": "2026-10-26T19:35:33.067080Z",
     "shell.execute_reply": "2026-10-26T19:35:33.066722Z"
    },
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Leo: $350.00\n",
      "Student accounts can withdraw at most $200 at a time\n",
      "True\n",
      "True\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "class Account:\n",
    "    def __init__(self, owner, balance=0.0):\n",
    "        self.owner = owner\n",
    "        self.balance = balance\n",
    "\n",
    "    def withdraw(self, amount):\n",
    "        if amount > self.balance:\n",
    "            raise ValueError('Insufficient funds')\n",
    "        self.balance -= amount\n",
    "\n",
    "    def __str__(self):\n",
    "        return f'{self.owner}: ${self.balance:.2f}'\n",
    "\n",
    "class StudentAccount(Account):\n",
    "    def __init__(self, owner, balance, school):\n",
    "        super().__init__(owner, balance)\n",
    "        self.school = school\n",
    "\n",
    "    def withdraw(self, amount):\n",
    "        if amount > 200:\n",
    "            raise ValueError('Student accounts can withdraw at most $200 at a time')\n",
    "        super().withdraw(amount)\n",
    "\n",
    "s = StudentAccount('Leo', 500, 'State U')\n",
    "s.withdraw(150)\n",
    "print(s)\n",
    "\n",
    "try:\n",
    "    s.withdraw(250)\n",
    "except ValueError as e:\n",
    "    print(e)\n",
    "\n",
    "print(isinstance(s, Account))\n",
    "print(issubclass(StudentAccount, Account))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "new-cefe5105",
   "metadata": {},
   "source": [
    "## Abstraction\n",
    "\n",
    "**Abstraction** means exposing *what* an object can do while hiding *how* it does it. Callers interact with a clean public interface and never need to know the internal logic. For example, you can call `sorted()` without knowing Python's sorting algorithm, use `list.append()` without knowing how lists are stored in memory, or call `acct.deposit()` without knowing what happens inside. Good abstraction makes complex systems feel simple.\n",
    "\n",
    "While inheritance provides a mechanism for one class to reuse another's code, abstraction is a design goal for hiding complexity behind a simple **interface**.\n",
    "\n",
    "Here the `BankAccount` class is a good example. A caller using `deposit`, `withdraw`, or `transfer_to` does not need to know:\n",
    "\n",
    "- how `withdraw` validates the amount\n",
    "- how `transfer_to` coordinates two accounts\n",
    "- how `_balance` is stored internally\n",
    "\n",
    "The caller only needs the interface: the method names and what they do."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-new-cefe5105",
   "metadata": {},
   "source": [
    "```{index} abstraction\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "id": "new-200d8f39",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2026-04-29T07:19:15.267256Z",
     "start_time": "2026-04-29T07:19:15.257224Z"
    },
    "execution": {
     "iopub.execute_input": "2026-10-26T19:35:33.068103Z",
     "iopub.status.busy": "2026-10-26T19:35:33.068031Z",
     "iopub.status.idle": "2026-10-26T19:35:33.069697Z",
     "shell.execute_reply": "2026-10-26T19:35:33.069430Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "S-3001: Eve - $3500.00\n",
      "B-3001: Eve Co - $3700.00\n"
     ]
    }
   ],
   "source": [
    "eve_savings  = SavingsAccount('S-3001', 'Eve', 2000.00, rate=0.02)\n",
    "eve_business = BusinessAccount('B-3001', 'Eve Co', 5000.00, transaction_fee=8.0)\n",
    "\n",
    "# None of these callers need to know the internal validation or storage logic\n",
    "eve_savings.deposit(500)\n",
    "eve_business.withdraw(300)\n",
    "eve_business.transfer_to(eve_savings, 1000)\n",
    "\n",
    "print(eve_savings)\n",
    "print(eve_business)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "57eb6196",
   "metadata": {},
   "source": [
    "### Abstract Base Classes (`abc`)\n",
    "\n",
    "Python supports abstraction explicitly through the built-in `abc` module (**A**bstract **B**ase **C**lasses). An Abstract Base Class (ABC) formalizes that pattern by declaring a contract: any subclass must implement certain methods. Calling an abstract class, or a subclass that is missing one of those methods, raises a `TypeError` instead of creating an object. In other words, with ABC, an abstract base class defines a required interface, it declares methods that child classes **must** implement. \n",
    "\n",
    "To implement ABC, you need to import the `ABC` class and the `abstractmethod` decorator. \n",
    "\n",
    "```python\n",
    "from abc import ABC, abstractmethod\n",
    "\n",
    "class Account(ABC):\n",
    "    @abstractmethod\n",
    "    def month_end(self):\n",
    "        \"\"\"Apply end-of-month rules for this account type.\"\"\"\n",
    "        pass\n",
    "```\n",
    "\n",
    "In this design, `Account` is not meant to be instantiated directly. Instead, concrete subclasses such as `SavingsAccount` or `CheckingAccount` provide their own implementation of `month_end()`.\n",
    "\n",
    "After a class inherits from an `ABC`, two behavior rules matter:\n",
    "\n",
    "- The subclass **must implement** every **abstract method** before it can be instantiated.\n",
    "- Any function that expects the `ABC` type can use different subclasses interchangeably through the same method names.\n",
    "\n",
    "`ABC` is useful when you want to enforce a shared interface across related classes, not just rely on convention."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-57eb6196",
   "metadata": {},
   "source": [
    "```{index} abstract base class, abc module, abstractmethod decorator (@abstractmethod)\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "id": "5edd7312",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-26T19:35:33.070539Z",
     "iopub.status.busy": "2026-10-26T19:35:33.070485Z",
     "iopub.status.idle": "2026-10-26T19:35:33.072846Z",
     "shell.execute_reply": "2026-10-26T19:35:33.072538Z"
    },
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Charged $49.99 to card ending in 4242.\n",
      "Charged $49.99 via PayPal account student@example.com.\n"
     ]
    }
   ],
   "source": [
    "# Use case: unified payment processing interface with ABC\n",
    "from abc import ABC, abstractmethod\n",
    "\n",
    "class PaymentMethod(ABC):\n",
    "    @abstractmethod                 ### this decorator marks charge as an abstract method \n",
    "    def charge(self, amount):       ### that must be implemented by subclasses\n",
    "        \"\"\"Return a message describing how payment is processed.\"\"\"\n",
    "        pass\n",
    "\n",
    "class CreditCard(PaymentMethod):\n",
    "    def __init__(self, last4):\n",
    "        self.last4 = last4\n",
    "\n",
    "    def charge(self, amount):       ### this method implements the abstract charge method defined in PaymentMethod\n",
    "        return f\"Charged ${amount:.2f} to card ending in {self.last4}.\"\n",
    "\n",
    "class PayPal(PaymentMethod):        ### another concrete implementation of PaymentMethod\n",
    "    def __init__(self, email):\n",
    "        self.email = email\n",
    "\n",
    "    def charge(self, amount):\n",
    "        return f\"Charged ${amount:.2f} via PayPal account {self.email}.\"\n",
    "\n",
    "\n",
    "def checkout(payment_method, amount):\n",
    "    if not isinstance(payment_method, PaymentMethod):\n",
    "        raise TypeError(\"checkout requires a PaymentMethod\")\n",
    "    return payment_method.charge(amount)\n",
    "\n",
    "methods = [CreditCard(\"4242\"), PayPal(\"student@example.com\")]\n",
    "for method in methods:\n",
    "    print(checkout(method, 49.99))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "595b2ae0",
   "metadata": {},
   "source": [
    "In the example above, both `CreditCard` and `PayPal` inherit from `PaymentMethod`, so each one must provide `charge(self, amount)`.\n",
    "\n",
    "That gives two practical benefits:\n",
    "\n",
    "- `checkout(...)` depends only on the abstract interface, not on a specific concrete class.\n",
    "- New payment types can be added later (for example, `GiftCard` or `BankTransfer`) without changing `checkout(...)`, as long as they inherit from `PaymentMethod` and implement `charge(...)`.\n",
    "\n",
    "This is abstraction in action: one stable contract, many concrete behaviors."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "id": "p2-ex-abs-q",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-26T19:35:33.075937Z",
     "iopub.status.busy": "2026-10-26T19:35:33.075802Z",
     "iopub.status.idle": "2026-10-26T19:35:33.077988Z",
     "shell.execute_reply": "2026-10-26T19:35:33.077336Z"
    },
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Abstraction\n",
    "#   1. Define an abstract class PaymentMethod(ABC) with an abstract\n",
    "#      method charge(self, amount).\n",
    "#   2. Define a concrete class GiftCard(PaymentMethod) with code and balance.\n",
    "#      Its charge(amount) raises ValueError if amount > balance; otherwise it\n",
    "#      subtracts amount and returns a message such as\n",
    "#      'Charged $20.00 to gift card GC-77; $30.00 left.'\n",
    "#   3. Try to create PaymentMethod() inside try/except TypeError and print\n",
    "#      'Cannot instantiate PaymentMethod'.\n",
    "#   4. Create GiftCard('GC-77', 50.0) and print the result of charge(20).\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "### Your code ends here."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "id": "p2-ex-abs-s",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-26T19:35:33.081574Z",
     "iopub.status.busy": "2026-10-26T19:35:33.081019Z",
     "iopub.status.idle": "2026-10-26T19:35:33.104300Z",
     "shell.execute_reply": "2026-10-26T19:35:33.102168Z"
    },
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Cannot instantiate PaymentMethod\n",
      "Charged $20.00 to gift card GC-77; $30.00 left.\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "from abc import ABC, abstractmethod\n",
    "\n",
    "class PaymentMethod(ABC):\n",
    "    @abstractmethod\n",
    "    def charge(self, amount):\n",
    "        pass\n",
    "\n",
    "class GiftCard(PaymentMethod):\n",
    "    def __init__(self, code, balance):\n",
    "        self.code = code\n",
    "        self.balance = balance\n",
    "\n",
    "    def charge(self, amount):\n",
    "        if amount > self.balance:\n",
    "            raise ValueError('Gift card balance too low')\n",
    "        self.balance -= amount\n",
    "        return f'Charged ${amount:.2f} to gift card {self.code}; ${self.balance:.2f} left.'\n",
    "\n",
    "try:\n",
    "    PaymentMethod()\n",
    "except TypeError:\n",
    "    print('Cannot instantiate PaymentMethod')\n",
    "\n",
    "card = GiftCard('GC-77', 50.0)\n",
    "print(card.charge(20))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch09-0902-exercises",
   "metadata": {},
   "source": [
    "## Exercises\n",
    "\n",
    "This task combines all four pillars in one small design."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "id": "b1aafd06",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-26T19:35:33.110719Z",
     "iopub.status.busy": "2026-10-26T19:35:33.110290Z",
     "iopub.status.idle": "2026-10-26T19:35:33.113753Z",
     "shell.execute_reply": "2026-10-26T19:35:33.113115Z"
    },
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Four Pillars Review\n",
    "#   Create a small OOP example that demonstrates all four pillars.\n",
    "#   1. Define class Wallet with owner and _cash, plus a read-only cash property.\n",
    "#   2. Add deposit(amount) and spend(amount) methods.\n",
    "#      If spend amount is greater than _cash, raise ValueError.\n",
    "#   3. Define class SavingsWallet(Wallet) that adds apply_interest(rate).\n",
    "#   4. Define abstract class Notifier with abstract method send(amount).\n",
    "#      Implement EmailNotifier and SMSNotifier, each returning a message string.\n",
    "#   5. Create one SavingsWallet, call deposit, spend, and apply_interest.\n",
    "#   6. Put both notifier types in one list and call send(w.cash) in one loop.\n",
    "#   7. Print wallet cash and both notifier messages.\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "### Your code ends here."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "id": "d6f5f57a",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-26T19:35:33.115058Z",
     "iopub.status.busy": "2026-10-26T19:35:33.114971Z",
     "iopub.status.idle": "2026-10-26T19:35:33.121441Z",
     "shell.execute_reply": "2026-10-26T19:35:33.120886Z"
    },
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "93.5\n",
      "Email sent: wallet balance is $93.50\n",
      "SMS sent: wallet balance is $93.50\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "from abc import ABC, abstractmethod\n",
    "\n",
    "class Wallet:\n",
    "    def __init__(self, owner, cash=0.0):\n",
    "        self.owner = owner\n",
    "        self._cash = float(cash)\n",
    "\n",
    "    @property\n",
    "    def cash(self):\n",
    "        return self._cash\n",
    "\n",
    "    def deposit(self, amount):\n",
    "        self._cash += amount\n",
    "\n",
    "    def spend(self, amount):\n",
    "        if amount > self._cash:\n",
    "            raise ValueError(\"Not enough cash\")\n",
    "        self._cash -= amount\n",
    "\n",
    "class SavingsWallet(Wallet):\n",
    "    def apply_interest(self, rate):\n",
    "        self._cash += self._cash * rate\n",
    "\n",
    "class Notifier(ABC):\n",
    "    @abstractmethod\n",
    "    def send(self, amount):\n",
    "        pass\n",
    "\n",
    "class EmailNotifier(Notifier):\n",
    "    def send(self, amount):\n",
    "        return f\"Email sent: wallet balance is ${amount:.2f}\"\n",
    "\n",
    "class SMSNotifier(Notifier):\n",
    "    def send(self, amount):\n",
    "        return f\"SMS sent: wallet balance is ${amount:.2f}\"\n",
    "\n",
    "w = SavingsWallet(\"Lia\", 100.0)\n",
    "w.deposit(25.0)\n",
    "w.spend(40.0)\n",
    "w.apply_interest(0.10)\n",
    "\n",
    "print(w.cash)\n",
    "for notifier in [EmailNotifier(), SMSNotifier()]:\n",
    "    print(notifier.send(w.cash))"
   ]
  }
 ],
 "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
}
