{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "l14-c000",
   "metadata": {},
   "source": [
    "# Lecture 16 - Objects 2: Inheritance and polymorphism\n",
    "\n",
    "**Authors:** Fiona McNeill, Matteo Degiacomi, Rayo Verweij, and Nigel Topham\n",
    "\n",
    "## Introduction\n",
    "\n",
    "In this lecture, we'll extend our knowledge of object-oriented programming by discussing how classes can build on other classes and examining relationships between classes in more detail.\n",
    "\n",
    "### Learning outcomes\n",
    "\n",
    "In this notebook, we'll discuss:\n",
    "\n",
    "- creating a subclass which inherits from another class;\n",
    "- extending initialisation and methods with `super()`;\n",
    "- overriding methods and using different objects through the same methods;\n",
    "- checking class relationships with `isinstance()`; and\n",
    "- marking attributes and methods as private with leading underscores.\n",
    "\n",
    "### Using the notebook\n",
    "\n",
    "Remember, this notebook is _yours_! You can edit each cell, for example by adding new examples or changing values to see what happens. Feel free to experiment!\n",
    "\n",
    "<details>\n",
    "<summary>Click to expand</summary>\n",
    "\n",
    "A common approach for learning how to read and write code in a structured way is called **PRIMM**:\n",
    "1. **Predict**: before running the code, look at it - do you understand each line? What do you think will happen?\n",
    "2. **Run**: now run the code and see what output you get.\n",
    "3. **Investigate**: did it go as you thought it would? If not, can you figure out why?\n",
    "4. **Modify**: now change the code and once again try to predict the output. If you got it wrong the first time, did you get it right now?\n",
    "5. **Make**: finally, try to write your own program from scratch using the skills you learned.\n",
    "\n",
    "You can apply steps 1-4 to each code cell in the notebook and many will have prediction prompts to help you get started. In addition, there will be challenges that ask you to put everything together yourself and execute step 5. There will often be multiple ways to solve these, but each challenge has a potential answer listed.\n",
    "\n",
    "</details>\n",
    "\n",
    "### Navigating the notebook\n",
    "\n",
    "A Jupyter notebook can be operated with your keyboard. Here is a **cheat sheet**:\n",
    "\n",
    "<details>\n",
    "<summary>Click to expand</summary>\n",
    "\n",
    "- To run the selected cell and move to the next cell, press <kbd>&#x21E7; Shift</kbd> + <kbd>&#x23ce; Enter</kbd>.\n",
    "- To run the selected cell and keep focus there, press <kbd>⌃ Ctrl</kbd> + <kbd>&#x23ce; Enter</kbd>.\n",
    "- To create a cell under the one currently highlighted, press <kbd>B</kbd>;\n",
    "- To delete the currently highlighted cell, press <kbd>D</kbd> twice (be careful with this one!) or press <kbd>X</kbd> to cut it;\n",
    "- To get help for a specific function, place the cursor within the function's brackets, hold <kbd>&#x21E7; Shift</kbd>, and press <kbd>&#x21E5; Tab</kbd>.\n",
    "\n",
    "</details>\n",
    "\n",
    "Watch out: **code cells remember what happened in cells before**. So, especially in the more complicated notebooks later down the line, make sure to always run **every** cell from top to bottom, as one might rely on a piece of code that came before it! If your results become confusing, use **Kernel > Restart Kernel** and then rerun all the completed cells in order.\n",
    "\n",
    "### Further reading and practice\n",
    "\n",
    "- Official Python tutorial: [Inheritance](https://docs.python.org/3/tutorial/classes.html#inheritance) and the [`isinstance()` reference](https://docs.python.org/3/library/functions.html#isinstance).\n",
    "- W3Schools: [Inheritance](https://www.w3schools.com/python/python_inheritance.asp), [Polymorphism](https://www.w3schools.com/python/python_polymorphism.asp), and [Encapsulation](https://www.w3schools.com/python/python_encapsulation.asp).\n",
    "- Helsinki Python MOOC: [Class hierarchies](https://programming-26.mooc.fi/part-10/1-class-hierarchies) and [Encapsulation](https://programming-26.mooc.fi/part-9/3-encapsulation) - though these go into more depth than we do here."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l14-c001",
   "metadata": {},
   "source": [
    "## 1. Inheritance\n",
    "\n",
    "Say we're building classes for an event management app. Online and in-person events both have a bunch of shared properties, such as a title and a capacity, but would also each need some different information. We could write two completely separate classes, `OnlineEvent` and `InPersonEvent`, but these would likely have some overlap between them. And remember: DRY! How could we do this more efficiently?\n",
    "\n",
    "**Inheritance** lets a class reuse the attributes and methods of another class. The original class is the **base class** or **superclass**; the new one is its **subclass**. To create a subclass, write the base class's name in parentheses after the new class name.\n",
    "\n",
    "**Predict:** `OnlineEvent` has no `description()` method in its own body. What happens when we call one?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "l14-c002",
   "metadata": {},
   "outputs": [],
   "source": [
    "class Event:\n",
    "    def __init__(self, title, capacity):\n",
    "        self.title = title\n",
    "        self.capacity = capacity\n",
    "\n",
    "    def description(self):\n",
    "        return f\"{self.title} (capacity {self.capacity})\"\n",
    "\n",
    "class OnlineEvent(Event):\n",
    "    pass\n",
    "\n",
    "seminar = OnlineEvent(\"Python seminar\", 80)\n",
    "print(seminar.description())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l14-c003",
   "metadata": {},
   "source": [
    "That's right, it prints the description of `Event`! This is because `OnlineEvent` has *inherited* the attributes and methods of its **parent** class. When calling `seminar.description()`, Python first looks for `description()` in `OnlineEvent`, and as it cannot find it, then looks for it in `Event`.\n",
    "\n",
    "The same happens for dunder methods such as `__init__()`, which is why we can call `OnlineEvent()` without specifying a constructor in `OnlineEvent`.\n",
    "\n",
    "Before making a subclass, try describing the relationship as \"a *subclass* is a kind of *superclass*\". The specialised object should still make sense wherever the general kind is expected. For example, a `Dog` subclass could inherit from an `Animal` superclass, or a `Book` subclass could inherit from a more generic `LibraryItem`."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l14-c004",
   "metadata": {
    "tags": [
     "exercise"
    ]
   },
   "source": [
    "<div class=\"alert alert-success\">\n",
    "<b>Try it yourself: inherit a method</b>\n",
    "\n",
    "Create a `Vehicle` class with a `name` attribute and a `move()` method that returns a message. Make `Bicycle` a subclass of `Vehicle`. Create a bicycle and call its inherited `move()`.\n",
    "</div>\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "l14-c005",
   "metadata": {
    "tags": [
     "exercise"
    ]
   },
   "outputs": [],
   "source": [
    "# Your code here!\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l14-c006",
   "metadata": {
    "tags": [
     "solution"
    ]
   },
   "source": [
    "<details>\n",
    "<summary><b>Click for a possible solution</b></summary>\n",
    "\n",
    "```python\n",
    "class Vehicle:\n",
    "    def __init__(self, name):\n",
    "        self.name = name\n",
    "\n",
    "    def move(self):\n",
    "        return f\"{self.name} is moving\"\n",
    "\n",
    "class Bicycle(Vehicle):\n",
    "    pass\n",
    "\n",
    "bike = Bicycle(\"city bike\")\n",
    "print(bike.move())\n",
    "```\n",
    "</details>\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l14-c007",
   "metadata": {},
   "source": [
    "### Adding subclass attributes with `super()`\n",
    "\n",
    "Now let's actually add some attributes specific to our subclass.\n",
    "\n",
    "Building an object out of other objects is called **composition**. In a subclass, we can use `super()` to access any methods on our parent class. This means that when we give a subclass its own `__init__()` constructor, we can still instantiate the attributes inherited from the parent class using `super().__init__()`.\n",
    "\n",
    "This is necessary as defining a method with the same name as an inherited one **overrides** that method. Our new constructor runs instead of the inherited constructor, so we need to ask for the base class's setup explicitly.\n",
    "\n",
    "**Predict:** Which line creates each of the three attributes printed below?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "l14-c008",
   "metadata": {},
   "outputs": [],
   "source": [
    "class Event:\n",
    "    def __init__(self, title, capacity):\n",
    "        self.title = title\n",
    "        self.capacity = capacity\n",
    "\n",
    "    def description(self):\n",
    "        return f\"{self.title} (capacity {self.capacity})\"\n",
    "\n",
    "class OnlineEvent(Event):\n",
    "    def __init__(self, title, capacity, platform):\n",
    "        super().__init__(title, capacity)\n",
    "        self.platform = platform\n",
    "\n",
    "webinar = OnlineEvent(\"Data skills\", 200, \"Collaborate\")\n",
    "print(webinar.title, webinar.capacity, webinar.platform)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l14-c009",
   "metadata": {},
   "source": [
    "In this example, the base initialiser creates `title` and `capacity` and the subclass initialiser creates `platform`. As a result, all three attributes are available on our `webinar` object.\n",
    "\n",
    "If we removed the `super().__init__()` line, `platform` would still be created, but attempting to access `title` would raise an `AttributeError`. Defining a subclass initialiser doesn't automatically run the base initialiser as well!"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l14-c010",
   "metadata": {
    "tags": [
     "exercise"
    ]
   },
   "source": [
    "<div class=\"alert alert-success\">\n",
    "<b>Try it yourself: extend the initialiser</b>\n",
    "\n",
    "Starting from your `Vehicle` class, define `ElectricBicycle(Vehicle)` with a `battery_level` attribute. Call `super().__init__()` to set up the name. Add `charge(amount)`, which increases the level but stops at 100. For this exercise, assume the initial level is between 0 and 100 and the amount is non-negative. Test a charge that reaches the limit.\n",
    "</div>\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "l14-c011",
   "metadata": {
    "tags": [
     "exercise"
    ]
   },
   "outputs": [],
   "source": [
    "# Write code for Vehicle first if you did not do the previous challenge\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l14-c012",
   "metadata": {
    "tags": [
     "solution"
    ]
   },
   "source": [
    "<details>\n",
    "<summary><b>Click for a possible solution</b></summary>\n",
    "\n",
    "See the previous challenge for the base `Vehicle` class.\n",
    "\n",
    "```python\n",
    "class ElectricBicycle(Vehicle):\n",
    "    def __init__(self, name, battery_level):\n",
    "        super().__init__(name)\n",
    "        self.battery_level = battery_level\n",
    "\n",
    "    def charge(self, amount):\n",
    "        self.battery_level += amount\n",
    "        if self.battery_level > 100:\n",
    "            self.battery_level = 100\n",
    "\n",
    "bike = ElectricBicycle(\"e-bike\", 75)\n",
    "bike.charge(30)\n",
    "print(bike.name, bike.battery_level)\n",
    "```\n",
    "</details>\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l14-c013",
   "metadata": {},
   "source": [
    "## 2. Polymorphism\n",
    "\n",
    "We can override any method, not just `__init__()`. For example, an in-person event should include a room, while an online event should include a video calling platform. Each can reuse the general event description by calling `super().description()` and add their own extra information.\n",
    "\n",
    "**Polymorphism** means that the same operation can work with different kinds of objects, with each object providing its own behaviour. Watch the loop below: it calls `description()` in exactly the same way for all three events.\n",
    "\n",
    "**Predict:** Which implementation of `description()` runs for each list element?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "l14-c014",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Make sure to run the cell above with the initial base class before running this one!\n",
    "\n",
    "class InPersonEvent(Event):\n",
    "    def __init__(self, title, capacity, room):\n",
    "        super().__init__(title, capacity)\n",
    "        self.room = room\n",
    "\n",
    "    def description(self):\n",
    "        return f\"{super().description()} in {self.room}\"\n",
    "\n",
    "class OnlineEvent(Event):\n",
    "    def __init__(self, title, capacity, platform):\n",
    "        super().__init__(title, capacity)\n",
    "        self.platform = platform\n",
    "\n",
    "    def description(self):\n",
    "        return f\"{super().description()} via {self.platform}\"\n",
    "\n",
    "events = [\n",
    "    Event(\"Welcome\", 100),\n",
    "    InPersonEvent(\"Lab\", 30, \"G.07\"),\n",
    "    OnlineEvent(\"Q&A\", 200, \"Collaborate\"),\n",
    "]\n",
    "for event in events:\n",
    "    print(event.description())\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l14-c015",
   "metadata": {},
   "source": [
    "The loop works as long as each object has a suitable `description()` method.\n",
    "\n",
    "In Python, classes don't have to share a base class for this to work. An unrelated class with a suitable `description()` method could also be used by this loop, because as discussed, Python is *dynamically* rather than *statically* typed. Depending on what an object can do, rather than requiring a particular class name, is often called **duck typing**. Other languages, such as Java, have stricter rules for this."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l14-c016",
   "metadata": {
    "tags": [
     "exercise"
    ]
   },
   "source": [
    "<div class=\"alert alert-success\">\n",
    "<b>Challenge: Override a method</b>\n",
    "\n",
    "Define `Bus(Vehicle)` and `Bicycle(Vehicle)`, each with a different `move()` message. Create one of each, put them in a list, and print the result of each object's `move()` method in a loop. The loop should work if you later add another kind of vehicle with a suitable method.\n",
    "</div>\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "l14-c017",
   "metadata": {
    "tags": [
     "exercise"
    ]
   },
   "outputs": [],
   "source": [
    "# Inherit again from your Vehicle class above\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l14-c018",
   "metadata": {
    "tags": [
     "solution"
    ]
   },
   "source": [
    "<details>\n",
    "<summary><b>Click for a possible solution</b></summary>\n",
    "\n",
    "```python\n",
    "class Bus(Vehicle):\n",
    "    def move(self):\n",
    "        return f\"{self.name} follows its route\"\n",
    "\n",
    "class Bicycle(Vehicle):\n",
    "    def move(self):\n",
    "        return f\"{self.name} uses the cycle lane\"\n",
    "\n",
    "vehicles = [Bus(\"number 30\"), Bicycle(\"city bike\")]\n",
    "for vehicle in vehicles:\n",
    "    print(vehicle.move())\n",
    "```\n",
    "</details>\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l14-c019",
   "metadata": {},
   "source": [
    "## 3. Checking class relationships\n",
    "\n",
    "We have already seen `type(value)`, which tells us to which class a value belongs.\n",
    "\n",
    "By contrast, `isinstance(value, Class)` tells us whether a value is an instance of that class *or one of its subclasses*.\n",
    "\n",
    "The second argument of `isinstance()` can also be a tuple of classes. For example, `isinstance(value, (Event, str))` accepts an event, any event subclass, or a string.\n",
    "\n",
    "**Predict:** How many of the checks below return `True`?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "l14-c020",
   "metadata": {},
   "outputs": [],
   "source": [
    "lab = InPersonEvent(\"Lab\", 30, \"G.07\")\n",
    "print(isinstance(lab, InPersonEvent))\n",
    "print(isinstance(lab, Event))\n",
    "print(type(lab) == Event)\n",
    "print(isinstance(lab, (Event, str)))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l14-c021",
   "metadata": {},
   "source": [
    "The exact class of `lab` is `InPersonEvent`, but it also belongs to the broader `Event` family. Therefore, all but `type(lab) == Event` return `True`."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l14-c022",
   "metadata": {
    "tags": [
     "exercise"
    ]
   },
   "source": [
    "<div class=\"alert alert-success\">\n",
    "<b>Try it yourself: check the family</b>\n",
    "\n",
    "Create a list containing a `Vehicle`, a `Bus`, and a string. Loop over it and print `move()` only for instances of the `Vehicle` family. Make sure that the bus is included.\n",
    "</div>\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "l14-c023",
   "metadata": {
    "tags": [
     "exercise"
    ]
   },
   "outputs": [],
   "source": [
    "# Your code here!\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l14-c024",
   "metadata": {
    "tags": [
     "solution"
    ]
   },
   "source": [
    "<details>\n",
    "<summary><b>Click for a possible solution</b></summary>\n",
    "\n",
    "```python\n",
    "values = [Vehicle(\"generic\"), Bus(\"number 30\"), \"not a vehicle\"]\n",
    "for value in values:\n",
    "    if isinstance(value, Vehicle):\n",
    "        print(value.move())\n",
    "```\n",
    "</details>\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l14-c025",
   "metadata": {},
   "source": [
    "## 4. Encapsulation\n",
    "\n",
    "A key benefit of programming in an object-oriented way - that is, defining your data and methods through a series of classes - is that it makes it easy to group related data and operations on them together, with a clear interface for other code. This practice of \"protecting\" data inside of a class is called **encapsulation**.\n",
    "\n",
    "Some languages, such as Java, allow for very strict encapsulation by specifying whether attributes and methods are **public** or **private**. In those languages, public attributes and methods can be accessed by any other piece of the code, whereas private ones can only be accessed from *within* the class. This can help prevent errors as it makes it more difficult to accidentally update variables in different pieces of code.\n",
    "\n",
    "Python does not have a complete mechanism for enforcing private variables. However, by convention, Python programmers often use leading underscores, such as `_name`, to mark that an attribute or method should be *treated* as private. While there is technically nothing preventing you from using these variables in other parts of code, it is a sign to yourself and your collaborators that you should use public methods instead.\n",
    "\n",
    "Take a look at the following example, which is a class for recording a battery's charge. In the class below, `_normalise_level()` limits a value to the permitted range. Both initialisation and charging use it, so we only have to write that rule once. `level()` gives callers a way to read the current level.\n",
    "\n",
    "**Predict:** Does a starting level of 120 produce an object with level 120? What does the charge change it to?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "l14-c026",
   "metadata": {},
   "outputs": [],
   "source": [
    "class Battery:\n",
    "    def __init__(self, level):\n",
    "        self._level = self._normalise_level(level)\n",
    "\n",
    "    def _normalise_level(self, level):\n",
    "        if level < 0:\n",
    "            return 0\n",
    "        if level > 100:\n",
    "            return 100\n",
    "        return level\n",
    "\n",
    "    def charge(self, amount):\n",
    "        if amount < 0:\n",
    "            raise ValueError(\"charge amount must be non-negative\")\n",
    "        self._level = self._normalise_level(self._level + amount)\n",
    "\n",
    "    def level(self):\n",
    "        return self._level\n",
    "\n",
    "battery = Battery(120)\n",
    "battery.charge(20)\n",
    "print(battery.level())\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l14-c027",
   "metadata": {},
   "source": [
    "A caller can use `battery.charge(20)` and `battery.level()` without knowing how the level is stored or checked. Those public methods form the class's **interface**. `_level` is marked as private, letting users of the class know that they should not directly update it themselves.\n",
    "\n",
    "Try changing the initial level to `-10`, then to `90`. In each case, check that charging keeps the level in range. A negative charge amount raises `ValueError` - if we wanted a discharge operation, we'd give it a separate method with its own clear meaning."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l14-c028",
   "metadata": {
    "tags": [
     "exercise"
    ]
   },
   "source": [
    "<div class=\"alert alert-success\">\n",
    "<b>Challenge: Keep bookings within capacity</b>\n",
    "\n",
    "Create `CapacityEvent(Event)` with an internal `_attendees` count starting at zero. Give it `book(places)` and `available_places()` methods. An internal `_can_book(places)` method should check for a positive number of places and enough remaining capacity. Return `False` for a rejected booking and leave the count unchanged. Assume whole-number capacities and bookings. Test a successful booking, one that's over capacity, and one that has zero available spots.\n",
    "</div>\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "l14-c029",
   "metadata": {
    "tags": [
     "exercise"
    ]
   },
   "outputs": [],
   "source": [
    "# Inherit from the Event class earlier in this notebook\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l14-c030",
   "metadata": {
    "tags": [
     "solution"
    ]
   },
   "source": [
    "<details><summary><b>Click for a possible solution</b></summary>\n",
    "\n",
    "```python\n",
    "class CapacityEvent(Event):\n",
    "    def __init__(self, title, capacity):\n",
    "        if capacity < 0:\n",
    "            raise ValueError(\"capacity must be non-negative\")\n",
    "        super().__init__(title, capacity)\n",
    "        self._attendees = 0\n",
    "\n",
    "    def _can_book(self, places):\n",
    "        return places > 0 and self._attendees + places <= self.capacity\n",
    "\n",
    "    def book(self, places):\n",
    "        if not self._can_book(places):\n",
    "            return False\n",
    "        self._attendees += places\n",
    "        return True\n",
    "\n",
    "    def available_places(self):\n",
    "        return self.capacity - self._attendees\n",
    "\n",
    "event = CapacityEvent(\"Workshop\", 20)\n",
    "assert event.book(12) is True\n",
    "assert event.available_places() == 8\n",
    "assert event.book(10) is False\n",
    "assert event.book(0) is False\n",
    "assert event.available_places() == 8\n",
    "```\n",
    "</details>\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l14-consolidation-prompt",
   "metadata": {
    "tags": [
     "exercise"
    ]
   },
   "source": [
    "## Consolidation challenge\n",
    "\n",
    "Let's wrap up by applying all that we've learned in a slightly different context.\n",
    "\n",
    "<div class=\"alert alert-success\">\n",
    "<b>Try it yourself: ping!</b>\n",
    "\n",
    "Create a base `Notification(recipient)` class with a `send(message)` method that returns the notification as a string.\n",
    "\n",
    "Then create `EmailNotification` and `SMSNotification` subclasses. Give email notifications an extra `subject` attribute and an SMS notifications a `sender` attribute. Each subclass should override `send(message)` with its own message format.\n",
    "\n",
    "In each subclass, use an internal `_valid_recipient()` method. Accept an email recipient if it contains `@`, and a phone recipient if it starts with `+`. The string method `text.startswith(prefix)` returns `True` when the text begins with that prefix. Raise `ValueError` when a recipient fails the rule.\n",
    "\n",
    "Put one of each notification in a list and call `send()` in a loop. Then test an invalid recipient and check that the expected exception is raised.\n",
    "</div>\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "l14-consolidation-work",
   "metadata": {
    "tags": [
     "exercise"
    ]
   },
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "id": "l14-consolidation-solution",
   "metadata": {
    "tags": [
     "solution"
    ]
   },
   "source": [
    "<details><summary><b>Click for a possible solution</b></summary>\n",
    "\n",
    "```python\n",
    "class Notification:\n",
    "    def __init__(self, recipient):\n",
    "        self.recipient = recipient\n",
    "\n",
    "    def send(self, message):\n",
    "        return f\"To {self.recipient}: {message}\"\n",
    "\n",
    "class EmailNotification(Notification):\n",
    "    def __init__(self, recipient, subject):\n",
    "        super().__init__(recipient)\n",
    "        self.subject = subject\n",
    "\n",
    "    def _valid_recipient(self):\n",
    "        return \"@\" in self.recipient\n",
    "\n",
    "    def send(self, message):\n",
    "        if not self._valid_recipient():\n",
    "            raise ValueError(\"email recipient must contain @\")\n",
    "        return f\"Email to {self.recipient} ({self.subject}): {message}\"\n",
    "\n",
    "class SMSNotification(Notification):\n",
    "    def __init__(self, recipient, sender):\n",
    "        super().__init__(recipient)\n",
    "        self.sender = sender\n",
    "\n",
    "    def _valid_recipient(self):\n",
    "        return self.recipient.startswith(\"+\")\n",
    "\n",
    "    def send(self, message):\n",
    "        if not self._valid_recipient():\n",
    "            raise ValueError(\"phone recipient must start with +\")\n",
    "        return f\"SMS from {self.sender} to {self.recipient}: {message}\"\n",
    "\n",
    "notifications = [\n",
    "    EmailNotification(\"a@example.org\", \"Timetable\"),\n",
    "    SMSNotification(\"+441234\", \"Teaching team\"),\n",
    "]\n",
    "for notification in notifications:\n",
    "    print(notification.send(\"Class starts at 10\"))\n",
    "\n",
    "try:\n",
    "    SMSNotification(\"1234\", \"Teaching team\").send(\"Hello\")\n",
    "except ValueError:\n",
    "    print(\"Invalid recipient was rejected\")\n",
    "else:\n",
    "    raise AssertionError(\"Invalid recipient was accepted\")\n",
    "```\n",
    "</details>\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l14-consolidation-summary",
   "metadata": {
    "tags": [
     "summary"
    ]
   },
   "source": [
    "## Summary\n",
    "\n",
    "Well done! You've now seen the basic building blocks of object-oriented programming: inheritance, composition, polymorphism, and encapsulation. While not an official feature of Python, we've also seen how you can mark values as private by convention.\n",
    "\n",
    "### Key terms\n",
    "\n",
    "<dl>\n",
    "\t<dt><b>Inheritance</b></dt>\n",
    "\t<dd>Building a class on another class, reusing and extending its behaviour.</dd>\n",
    "\t<dt><b>Superclass / base class / parent class</b></dt>\n",
    "\t<dd>The class from which another class inherits.</dd>\n",
    "\t<dt><b>Subclass / child class</b></dt>\n",
    "\t<dd>A class that inherits from a base class.</dd>\n",
    "\t<dt><b>Composition</b></dt>\n",
    "\t<dd>Building an object using other objects as its parts or attributes.</dd>\n",
    "\t<dt><b>Overriding</b></dt>\n",
    "\t<dd>Defining a method in a subclass with the same name as an inherited method.</dd>\n",
    "\t<dt><b>Polymorphism</b></dt>\n",
    "\t<dd>Using the same operation with different kinds of objects, each providing their own suitable behaviour.</dd>\n",
    "\t<dt><b>Duck typing</b></dt>\n",
    "\t<dd>Using the operations an object supports without requiring a particular class.</dd>\n",
    "\t<dt><b>Encapsulation</b></dt>\n",
    "\t<dd>Keeping state and the operations that manage it together behind a clear interface.</dd>\n",
    "\t<dt><b>Interface</b></dt>\n",
    "\t<dd>The operations that other code is expected to use with an object.</dd>\n",
    "</dl>\n",
    "\n",
    "### New syntax\n",
    "\n",
    "<dl>\n",
    "\t<dt><code>class SubClass(SuperClass):</code></dt>\n",
    "\t<dd>Define a subclass of <code>SuperClass</code>.</dd>\n",
    "\t<dt><code>super().__init__(attributes)</code></dt>\n",
    "\t<dd>Use the inherited initialiser for the current object.</dd>\n",
    "\t<dt><code>super().method()</code></dt>\n",
    "\t<dd>Call the inherited method as part of an overriding method.</dd>\n",
    "\t<dt><code>isinstance(value, ClassName)</code></dt>\n",
    "\t<dd>Check whether value is an instance of <code>ClassName</code> or one of its subclasses.</dd>\n",
    "\t<dt><code>isinstance(value, (ClassName1, ClassName2, ...))</code></dt>\n",
    "\t<dd>Accept an instance of any class in the tuple, including their subclasses.</dd>\n",
    "\t<dt><code>_privateName</code></dt>\n",
    "\t<dd>By convention, marking an attribute or method as private. Does not actually prevent access!</dd>\n",
    "</dl>\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "pygments_lexer": "ipython3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
