{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Topic 7: Classes and objects, modules and packages\n",
    "\n",
    "Asiman Data School, Module 1: Foundations of Python Programming. Week 4, Tuesday.\n",
    "\n",
    "This notebook follows the lesson page. Read the text, run the cell under it with Shift + Enter, then change the values in the cell and run it again. Seeing the output change is how the rules become clear.\n",
    "\n",
    "Run the cells from top to bottom. When a cell reads input, a small box appears: type the values there and press Enter. The practice problems are in a separate notebook, topic-07-practice.ipynb.\n",
    "\n",
    "Contents\n",
    "\n",
    "1. The four ideas of OOP in plain words\n",
    "2. Classes, objects and methods\n",
    "3. Encapsulation in Python\n",
    "4. Abstraction in Python\n",
    "5. Inheritance in Python\n",
    "6. Polymorphism in Python\n",
    "7. Modules and packages\n",
    "8. Common mistakes\n",
    "9. Solved problems (easy to medium-hard)\n",
    "10. Practice problems (try them yourself) (in topic-07-practice.ipynb)\n",
    "11. Check yourself (on the website)\n",
    "12. Quick summary"
   ],
   "id": "t07-000"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Introduction: classes and objects, modules and packages\n",
    "\n",
    "What matters most in this lesson. Four things matter most today: the difference between a class (the plan) and an object (one real thing); writing a class with `__init__`, `self`, attributes and methods; knowing what encapsulation, abstraction, inheritance and polymorphism mean, each with one example; and using a module with `import`.\n",
    "\n",
    "Writing your own inheritance and polymorphism is a first look. It becomes natural with practice, and in the rest of the course you will mostly use classes that other people wrote (NumPy arrays, pandas tables, models). There are 15 solved problems. Start with Level 1 and come back for the rest.\n",
    "\n",
    "A beginner-friendly guide to Object-Oriented Programming (OOP) and to modules and packages. It starts with the four big ideas of OOP in plain words, with real-life examples and no code: encapsulation, abstraction, inheritance and polymorphism. Then it shows how to write classes and create objects in Python, and comes back to each of the four ideas with code. After that it explains modules and packages: how to use code that other people wrote, and how to organise your own. Then it walks through 15 solved problems from easy to medium-hard. At the end there are practice problems.\n",
    "\n",
    "You should already know variables, data types, `if/else`, loops, functions, lists, dictionaries and `try/except`.\n",
    "\n",
    "## 1. The four ideas of OOP in plain words\n",
    "\n",
    "### 1.1 What is Object-Oriented Programming?\n",
    "\n",
    "Until now our programs had two separate things: data (variables, lists, dictionaries) and functions that work on the data. In a small program that is fine. In a big program it becomes hard to see which function belongs to which data.\n",
    "\n",
    "Object-Oriented Programming puts the two together. An object is one thing that has:\n",
    "\n",
    "- data about itself (called attributes), and\n",
    "- actions it can do (called methods).\n",
    "\n",
    "Real-life picture: a car. It has data (color, speed, amount of fuel) and actions (start, drive, brake). You do not think about \"a list of car data\" and \"a function for braking\" separately. You think about the car.\n",
    "\n",
    "You have already used objects. A list is an object: it has data (its items) and actions (`append`, `sort`, `pop`). A text is an object too: `\"hello\".upper()`.\n",
    "\n",
    "OOP stands on four ideas. This part explains each one in plain words. The code comes later.\n",
    "\n",
    "### 1.2 Encapsulation: keep things together, and protect them\n",
    "\n",
    "Encapsulation means two things:\n",
    "\n",
    "1. The data and the actions that work on it are kept together in one place (one \"capsule\").\n",
    "2. The data is protected: it can be changed only in the allowed ways.\n",
    "\n",
    "Real-life examples\n",
    "\n",
    "- A bank account. You cannot open the bank's database and type a new balance. You can only deposit and withdraw, and the bank checks every operation (you cannot withdraw more than you have).\n",
    "- A medicine capsule. The ingredients are packed inside one shell. You take the capsule, not the separate powders.\n",
    "- A car's engine under the hood. You change the speed with the pedals, not by touching the engine with your hands.\n",
    "\n",
    "Why it helps: the data cannot get into a wrong state (a negative balance, an age of -5), because every change goes through a method that checks it.\n",
    "\n",
    "### 1.3 Abstraction: show what it does, hide how it does it\n",
    "\n",
    "Abstraction means showing only the simple controls that a user needs, and hiding the complicated details.\n",
    "\n",
    "Real-life examples\n",
    "\n",
    "- Driving a car. You use the steering wheel, the pedals and the gear stick. You do not need to know how the engine burns fuel.\n",
    "- A coffee machine. You press one button, \"Coffee\". Inside, the machine heats water, grinds beans and pumps water. You see none of it.\n",
    "- A TV remote. One button changes the channel. The electronics behind it are hidden.\n",
    "\n",
    "Why it helps: you can use something without understanding its inside, and the inside can be changed later without changing how you use it.\n",
    "\n",
    "### 1.4 Encapsulation and abstraction are not the same\n",
    "\n",
    "They are close, and beginners often mix them up:\n",
    "\n",
    "|  | Encapsulation | Abstraction |\n",
    "| --- | --- | --- |\n",
    "| Question | How is the data kept safe? | What does the user need to see? |\n",
    "| Idea | pack data and methods together, and protect the data | hide the complicated steps behind a simple action |\n",
    "| Bank account | the balance can be changed only by deposit and withdraw | you press \"Withdraw\", and do not see how the bank records it |\n",
    "\n",
    "### 1.5 Inheritance: build on what already exists\n",
    "\n",
    "Inheritance means creating a new kind of thing from an existing one. The new one gets everything the old one has, and can add its own things or change some.\n",
    "\n",
    "Real-life examples\n",
    "\n",
    "- Children and parents. A child inherits features from the parents (eye color, height) and also has features of their own.\n",
    "- Vehicles. A car, a bus and a truck are all vehicles: each has wheels and an engine, and each can drive. A bus adds passenger seats, a truck adds a cargo area.\n",
    "- People at a school. A student and a teacher are both persons: each has a name and an age. A student also has grades, a teacher also has a subject.\n",
    "\n",
    "The existing kind is called the parent (or base) class. The new kind is the child class. The test is the words \"is a\": a dog is an animal, a student is a person.\n",
    "\n",
    "Why it helps: you write the shared parts once, in the parent, and do not repeat them in every child.\n",
    "\n",
    "### 1.6 Polymorphism: one name, many forms\n",
    "\n",
    "Polymorphism means that the same action works on different kinds of things, and each kind does it in its own way. The word means \"many forms\".\n",
    "\n",
    "Real-life examples\n",
    "\n",
    "- \"Speak!\" Say it to a dog and it barks. Say it to a cat and it meows. The command is the same, the result depends on who receives it.\n",
    "- The \"play\" button. On a music app it plays a song, on a video app it plays a film. One button, different behaviour.\n",
    "- \"Draw yourself.\" A circle draws a round shape, a square draws four sides. The request is the same.\n",
    "\n",
    "Why it helps: you can treat different objects in the same way (for example in one loop) without asking each time \"which kind are you?\".\n",
    "\n",
    "### 1.7 The four ideas in one table\n",
    "\n",
    "| Idea | In one sentence | Real-life example |\n",
    "| --- | --- | --- |\n",
    "| Encapsulation | keep data and its actions together, and protect the data | a bank account: only deposit and withdraw can change the balance |\n",
    "| Abstraction | show the simple controls, hide the details | a coffee machine: one button, many hidden steps |\n",
    "| Inheritance | make a new kind from an existing kind | a bus is a vehicle with passenger seats |\n",
    "| Polymorphism | one action, done differently by each kind | \"speak\": a dog barks, a cat meows |\n",
    "\n",
    "## 2. Classes, objects and methods\n",
    "\n",
    "### 2.1 Class and object\n",
    "\n",
    "- A class is a plan (a blueprint). It describes what data and what actions a kind of thing has.\n",
    "- An object is one real thing made from that plan.\n",
    "\n",
    "Real-life picture: the plan of a house is the class. The houses built from it are the objects. One plan, many houses, and each house has its own color and its own owner.\n",
    "\n",
    "| Class (the plan) | Objects (real things) |\n",
    "| --- | --- |\n",
    "| `Dog` | Rex, Bella, Max |\n",
    "| `Student` | Aylin, Murad |\n",
    "| `BankAccount` | Aylin's account, Murad's account |\n",
    "\n",
    "### 2.2 The simplest class\n",
    "\n",
    "Change it and run: create a second object, `bella = Dog()`, and print its type."
   ],
   "id": "t07-001"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Dog:\n",
    "    pass\n",
    "\n",
    "rex = Dog()\n",
    "print(type(rex))"
   ],
   "id": "t07-002"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- `class Dog:` creates the class. Class names start with a capital letter.\n",
    "- `Dog()` creates an object from the class. The object is also called an instance.\n",
    "- `pass` means \"nothing here yet\".\n",
    "\n",
    "### 2.3 Attributes and `__init__`\n",
    "\n",
    "To give every object its own data, we write a special method called `__init__` (two underscores on each side). Python runs it automatically when an object is created:\n",
    "\n",
    "Change it and run: create a third dog with your own name and age, and print them."
   ],
   "id": "t07-003"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Dog:\n",
    "    def __init__(self, name, age):\n",
    "        self.name = name\n",
    "        self.age = age\n",
    "\n",
    "rex = Dog(\"Rex\", 3)\n",
    "bella = Dog(\"Bella\", 5)\n",
    "\n",
    "print(rex.name, rex.age)\n",
    "print(bella.name, bella.age)"
   ],
   "id": "t07-004"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- `self.name = name` stores the value inside the object. `name` and `age` are the attributes of the object.\n",
    "- `rex.name` reads an attribute, with a dot.\n",
    "- Each object has its own values.\n",
    "\n",
    "### 2.4 What is `self`?\n",
    "\n",
    "`self` is the object itself. When you write `Dog(\"Rex\", 3)`, Python creates a new, empty object and passes it to `__init__` as the first parameter, `self`. You never pass it yourself.\n",
    "\n",
    "| You write | Python runs |\n",
    "| --- | --- |\n",
    "| `rex = Dog(\"Rex\", 3)` | `__init__(rex, \"Rex\", 3)` |\n",
    "\n",
    "Forgetting an argument gives an error:\n",
    "\n",
    "```python\n",
    "class Dog:\n",
    "    def __init__(self, name, age):\n",
    "        self.name = name\n",
    "        self.age = age\n",
    "\n",
    "rex = Dog(\"Rex\")\n",
    "```\n",
    "\n",
    "```\n",
    "TypeError: Dog.__init__() missing 1 required positional argument: 'age'\n",
    "```\n",
    "\n",
    "### 2.5 Changing and adding attributes\n",
    "\n",
    "Change it and run: change the name too: `rex.name = \"Max\"`."
   ],
   "id": "t07-005"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Dog:\n",
    "    def __init__(self, name, age):\n",
    "        self.name = name\n",
    "        self.age = age\n",
    "\n",
    "rex = Dog(\"Rex\", 3)\n",
    "rex.age = 4\n",
    "print(rex.age)"
   ],
   "id": "t07-006"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "An attribute that does not exist gives an `AttributeError`:\n",
    "\n",
    "```python\n",
    "class Dog:\n",
    "    def __init__(self, name, age):\n",
    "        self.name = name\n",
    "        self.age = age\n",
    "\n",
    "rex = Dog(\"Rex\", 3)\n",
    "print(rex.color)\n",
    "```\n",
    "\n",
    "```\n",
    "AttributeError: 'Dog' object has no attribute 'color'\n",
    "```\n",
    "\n",
    "### 2.6 A method is a function inside a class\n",
    "\n",
    "A method is an action the object can do. Its first parameter is always `self`, so it can use the object's own data:\n",
    "\n",
    "Change it and run: call `rex.birthday()` three times. How old is Rex now?"
   ],
   "id": "t07-007"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Dog:\n",
    "    def __init__(self, name, age):\n",
    "        self.name = name\n",
    "        self.age = age\n",
    "\n",
    "    def bark(self):\n",
    "        print(self.name, \"says: Woof!\")\n",
    "\n",
    "    def birthday(self):\n",
    "        self.age = self.age + 1\n",
    "\n",
    "rex = Dog(\"Rex\", 3)\n",
    "rex.bark()\n",
    "rex.birthday()\n",
    "print(rex.age)"
   ],
   "id": "t07-008"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- `rex.bark()` calls the method. Python passes `rex` as `self`.\n",
    "- A method can read the attributes (`bark`) and change them (`birthday`).\n",
    "\n",
    "### 2.7 Methods with parameters and return values\n",
    "\n",
    "Methods work like the functions you know. They can take more parameters and return a value:\n",
    "\n",
    "Change it and run: add a method `perimeter()` and print it."
   ],
   "id": "t07-009"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Rectangle:\n",
    "    def __init__(self, width, height):\n",
    "        self.width = width\n",
    "        self.height = height\n",
    "\n",
    "    def area(self):\n",
    "        return self.width * self.height\n",
    "\n",
    "    def scale(self, factor):\n",
    "        self.width = self.width * factor\n",
    "        self.height = self.height * factor\n",
    "\n",
    "room = Rectangle(4, 3)\n",
    "print(room.area())\n",
    "room.scale(2)\n",
    "print(room.width, room.height, room.area())"
   ],
   "id": "t07-010"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 2.8 Printing an object: `__str__`\n",
    "\n",
    "Printing an object shows something unreadable:"
   ],
   "id": "t07-011"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Dog:\n",
    "    def __init__(self, name, age):\n",
    "        self.name = name\n",
    "        self.age = age\n",
    "\n",
    "rex = Dog(\"Rex\", 3)\n",
    "print(rex)"
   ],
   "id": "t07-012"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Python shows the class name and the place of the object in memory (the numbers will be different on your computer).\n",
    "\n",
    "The special method `__str__` returns the text that `print` should show:\n",
    "\n",
    "Change it and run: change the text that `__str__` returns."
   ],
   "id": "t07-013"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Dog:\n",
    "    def __init__(self, name, age):\n",
    "        self.name = name\n",
    "        self.age = age\n",
    "\n",
    "    def __str__(self):\n",
    "        return f\"{self.name} ({self.age} years old)\"\n",
    "\n",
    "rex = Dog(\"Rex\", 3)\n",
    "print(rex)"
   ],
   "id": "t07-014"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 2.9 Many objects in a list\n",
    "\n",
    "Objects are values, so they can be stored in a list and used in a loop:\n",
    "\n",
    "Change it and run: add a fourth student to the list. The loop needs no change."
   ],
   "id": "t07-015"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Student:\n",
    "    def __init__(self, name, grade):\n",
    "        self.name = name\n",
    "        self.grade = grade\n",
    "\n",
    "    def passed(self):\n",
    "        return self.grade >= 50\n",
    "\n",
    "students = [Student(\"Aylin\", 85), Student(\"Murad\", 42), Student(\"Leyla\", 78)]\n",
    "\n",
    "for student in students:\n",
    "    if student.passed():\n",
    "        print(student.name, \"passed\")\n",
    "    else:\n",
    "        print(student.name, \"failed\")"
   ],
   "id": "t07-016"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 2.10 An attribute shared by all objects\n",
    "\n",
    "An attribute written directly in the class (not in `__init__`) belongs to the class and is shared by all its objects:\n",
    "\n",
    "Change it and run: add a third dog. It has the species `\"dog\"` too."
   ],
   "id": "t07-017"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Dog:\n",
    "    species = \"dog\"\n",
    "\n",
    "    def __init__(self, name):\n",
    "        self.name = name\n",
    "\n",
    "rex = Dog(\"Rex\")\n",
    "bella = Dog(\"Bella\")\n",
    "print(rex.name, rex.species)\n",
    "print(bella.name, bella.species)"
   ],
   "id": "t07-018"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "|  | Instance attribute | Class attribute |\n",
    "| --- | --- | --- |\n",
    "| Written | in `__init__`, as `self.name = ...` | directly in the class |\n",
    "| Belongs to | one object | all objects of the class |\n",
    "| Example | the name of each dog | the species of all dogs |\n",
    "\n",
    "## 3. Encapsulation in Python\n",
    "\n",
    "The idea again: keep the data and its methods together, and let the data change only in the allowed ways.\n",
    "\n",
    "### 3.1 The problem: data that anyone can break\n",
    "\n",
    "Change it and run: set the balance to any value you like. Nothing stops you."
   ],
   "id": "t07-019"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "class BankAccount:\n",
    "    def __init__(self, owner, balance):\n",
    "        self.owner = owner\n",
    "        self.balance = balance\n",
    "\n",
    "account = BankAccount(\"Aylin\", 100)\n",
    "account.balance = -5000\n",
    "print(account.balance)"
   ],
   "id": "t07-020"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Nothing stops a wrong value. A negative balance makes no sense, but the object accepts it.\n",
    "\n",
    "### 3.2 The solution: change the data only through methods\n",
    "\n",
    "Change it and run: deposit 1000, then withdraw 200, and print the balance."
   ],
   "id": "t07-021"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "class BankAccount:\n",
    "    def __init__(self, owner, balance):\n",
    "        self.owner = owner\n",
    "        self._balance = balance\n",
    "\n",
    "    def deposit(self, amount):\n",
    "        if amount <= 0:\n",
    "            print(\"The amount must be positive\")\n",
    "            return\n",
    "        self._balance = self._balance + amount\n",
    "\n",
    "    def withdraw(self, amount):\n",
    "        if amount > self._balance:\n",
    "            print(\"Not enough money\")\n",
    "            return\n",
    "        self._balance = self._balance - amount\n",
    "\n",
    "    def get_balance(self):\n",
    "        return self._balance\n",
    "\n",
    "account = BankAccount(\"Aylin\", 100)\n",
    "account.deposit(50)\n",
    "account.withdraw(500)\n",
    "account.deposit(-20)\n",
    "print(account.get_balance())"
   ],
   "id": "t07-022"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- The balance is stored in `_balance`. The underscore at the start is a message to other programmers: \"this is internal, do not touch it directly\".\n",
    "- `deposit` and `withdraw` are the only allowed ways to change it, and they check every change.\n",
    "- `get_balance` lets others read the value.\n",
    "\n",
    "This is the bank account from Part 1: you cannot type a new balance, you can only deposit and withdraw.\n",
    "\n",
    "### 3.3 How strong is the protection?\n",
    "\n",
    "| Name | Meaning | Can it be reached from outside? |\n",
    "| --- | --- | --- |\n",
    "| `balance` | public: anyone may use it | yes |\n",
    "| `_balance` | internal: please do not touch | yes, but you should not |\n",
    "| `__balance` | private: Python hides the name | not by this name |\n",
    "\n",
    "One underscore is only an agreement. Two underscores make Python hide the name:\n",
    "\n",
    "```python\n",
    "class BankAccount:\n",
    "    def __init__(self, balance):\n",
    "        self.__balance = balance\n",
    "\n",
    "    def get_balance(self):\n",
    "        return self.__balance\n",
    "\n",
    "account = BankAccount(100)\n",
    "print(account.get_balance())\n",
    "print(account.__balance)\n",
    "```\n",
    "\n",
    "```\n",
    "100\n",
    "AttributeError: 'BankAccount' object has no attribute '__balance'. Did you mean: 'get_balance'?\n",
    "```\n",
    "\n",
    "In most Python programs, one underscore is enough.\n",
    "\n",
    "### 3.4 Raising an error instead of printing\n",
    "\n",
    "In the last lesson we learned that a function should raise an error when a value is not acceptable. The same is true for methods:\n",
    "\n",
    "Change it and run: withdraw 60 instead of 500. No error is raised."
   ],
   "id": "t07-023"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "class BankAccount:\n",
    "    def __init__(self, owner, balance):\n",
    "        self.owner = owner\n",
    "        self._balance = balance\n",
    "\n",
    "    def withdraw(self, amount):\n",
    "        if amount > self._balance:\n",
    "            raise ValueError(\"Not enough money\")\n",
    "        self._balance = self._balance - amount\n",
    "\n",
    "account = BankAccount(\"Aylin\", 100)\n",
    "try:\n",
    "    account.withdraw(500)\n",
    "except ValueError as error:\n",
    "    print(\"Problem:\", error)"
   ],
   "id": "t07-024"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 4. Abstraction in Python\n",
    "\n",
    "The idea again: show a simple action, hide the steps behind it.\n",
    "\n",
    "### 4.1 One simple method, several hidden steps\n",
    "\n",
    "Change it and run: add a fourth hidden step, `_add_milk`, and call it inside `make_coffee`."
   ],
   "id": "t07-025"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "class CoffeeMachine:\n",
    "    def _heat_water(self):\n",
    "        print(\"  heating the water\")\n",
    "\n",
    "    def _grind_beans(self):\n",
    "        print(\"  grinding the beans\")\n",
    "\n",
    "    def _pour(self):\n",
    "        print(\"  pouring the coffee\")\n",
    "\n",
    "    def make_coffee(self):\n",
    "        print(\"Making coffee:\")\n",
    "        self._heat_water()\n",
    "        self._grind_beans()\n",
    "        self._pour()\n",
    "        print(\"Your coffee is ready\")\n",
    "\n",
    "machine = CoffeeMachine()\n",
    "machine.make_coffee()"
   ],
   "id": "t07-026"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The user of the class needs to know one method: `make_coffee()`. The three steps start with an underscore, because they are internal details. This is the coffee machine from Part 1: one button.\n",
    "\n",
    "### 4.2 You use abstraction every day\n",
    "\n",
    "When you write `numbers.sort()`, you do not know (and do not need to know) how Python sorts the list. You only know what it does. That is abstraction."
   ],
   "id": "t07-027"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "numbers = [40, 10, 30]\n",
    "numbers.sort()\n",
    "print(numbers)\n",
    "print(len(\"hello\"))"
   ],
   "id": "t07-028"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 4.3 The inside can change, the outside stays the same\n",
    "\n",
    "Change it and run: create a second object for 0 degrees."
   ],
   "id": "t07-029"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Temperature:\n",
    "    def __init__(self, celsius):\n",
    "        self._celsius = celsius\n",
    "\n",
    "    def in_fahrenheit(self):\n",
    "        return self._celsius * 9 / 5 + 32\n",
    "\n",
    "today = Temperature(25)\n",
    "print(today.in_fahrenheit())"
   ],
   "id": "t07-030"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "If the class later stores the temperature in another way, every program that calls `in_fahrenheit()` still works. Users depend on the method, not on the details.\n",
    "\n",
    "## 5. Inheritance in Python\n",
    "\n",
    "The idea again: make a new class from an existing one. The child gets everything the parent has.\n",
    "\n",
    "### 5.1 A parent and a child\n",
    "\n",
    "Change it and run: add a class `Cat(Animal)` with a method `meow`."
   ],
   "id": "t07-031"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Animal:\n",
    "    def __init__(self, name):\n",
    "        self.name = name\n",
    "\n",
    "    def eat(self):\n",
    "        print(self.name, \"is eating\")\n",
    "\n",
    "class Dog(Animal):\n",
    "    def bark(self):\n",
    "        print(self.name, \"says: Woof!\")\n",
    "\n",
    "rex = Dog(\"Rex\")\n",
    "rex.eat()\n",
    "rex.bark()"
   ],
   "id": "t07-032"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- `class Dog(Animal):` means: `Dog` is a child of `Animal`.\n",
    "- `Dog` has no `__init__` and no `eat`, but both work: they are inherited from `Animal`.\n",
    "- `bark` is new: only dogs have it.\n",
    "\n",
    "### 5.2 Adding attributes in the child: `super()`\n",
    "\n",
    "When the child needs its own `__init__`, it calls the parent's `__init__` first with `super()`:\n",
    "\n",
    "Change it and run: add a method `passed()` to `Student` that returns `self.grade >= 50`."
   ],
   "id": "t07-033"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Person:\n",
    "    def __init__(self, name, age):\n",
    "        self.name = name\n",
    "        self.age = age\n",
    "\n",
    "    def introduce(self):\n",
    "        print(\"I am\", self.name)\n",
    "\n",
    "class Student(Person):\n",
    "    def __init__(self, name, age, grade):\n",
    "        super().__init__(name, age)\n",
    "        self.grade = grade\n",
    "\n",
    "aylin = Student(\"Aylin\", 20, 85)\n",
    "aylin.introduce()\n",
    "print(aylin.name, aylin.age, aylin.grade)"
   ],
   "id": "t07-034"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`super().__init__(name, age)` lets `Person` store the name and the age. Then `Student` adds the grade. Nothing is written twice.\n",
    "\n",
    "### 5.3 Changing a method in the child: overriding\n",
    "\n",
    "If the child defines a method with the same name as the parent's, the child's version is used. This is called overriding:\n",
    "\n",
    "Change it and run: give `Fish` its own `speak` method."
   ],
   "id": "t07-035"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Animal:\n",
    "    def __init__(self, name):\n",
    "        self.name = name\n",
    "\n",
    "    def speak(self):\n",
    "        print(self.name, \"makes a sound\")\n",
    "\n",
    "class Dog(Animal):\n",
    "    def speak(self):\n",
    "        print(self.name, \"says: Woof!\")\n",
    "\n",
    "class Fish(Animal):\n",
    "    pass\n",
    "\n",
    "Dog(\"Rex\").speak()\n",
    "Fish(\"Nemo\").speak()"
   ],
   "id": "t07-036"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`Dog` has its own `speak`. `Fish` has none, so it uses the parent's.\n",
    "\n",
    "### 5.4 \"Is a\": `isinstance`\n",
    "\n",
    "Change it and run: create `cat = Animal()` and check `isinstance(cat, Dog)`."
   ],
   "id": "t07-037"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Animal:\n",
    "    pass\n",
    "\n",
    "class Dog(Animal):\n",
    "    pass\n",
    "\n",
    "rex = Dog()\n",
    "print(isinstance(rex, Dog))\n",
    "print(isinstance(rex, Animal))\n",
    "print(isinstance(rex, str))"
   ],
   "id": "t07-038"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A dog is a dog, and a dog is an animal.\n",
    "\n",
    "| Word | Meaning | In the examples |\n",
    "| --- | --- | --- |\n",
    "| Parent (base) class | the existing class | `Animal`, `Person` |\n",
    "| Child class | the new class built on it | `Dog`, `Student` |\n",
    "| Inherit | get the attributes and methods of the parent | `rex.eat()` |\n",
    "| `super()` | the parent, used to call its methods | `super().__init__(name, age)` |\n",
    "| Override | replace a parent's method in the child | `Dog.speak` |\n",
    "\n",
    "## 6. Polymorphism in Python\n",
    "\n",
    "The idea again: the same method name, and each kind of object does it in its own way.\n",
    "\n",
    "### 6.1 One loop, different objects\n",
    "\n",
    "Change it and run: add a class `Duck` with `speak` and put a duck into the list."
   ],
   "id": "t07-039"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Dog:\n",
    "    def speak(self):\n",
    "        return \"Woof!\"\n",
    "\n",
    "class Cat:\n",
    "    def speak(self):\n",
    "        return \"Meow!\"\n",
    "\n",
    "class Cow:\n",
    "    def speak(self):\n",
    "        return \"Moo!\"\n",
    "\n",
    "animals = [Dog(), Cat(), Cow()]\n",
    "for animal in animals:\n",
    "    print(animal.speak())"
   ],
   "id": "t07-040"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The loop does not ask \"are you a dog or a cat?\". It calls `speak()`, and every object answers in its own way. This is \"Speak!\" from Part 1.\n",
    "\n",
    "### 6.2 Polymorphism with inheritance\n",
    "\n",
    "Often the classes share a parent, and each child overrides the same method:\n",
    "\n",
    "Change it and run: add a class `Triangle(Shape)` with a base and a height, and put one into the list."
   ],
   "id": "t07-041"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Shape:\n",
    "    def __init__(self, name):\n",
    "        self.name = name\n",
    "\n",
    "    def area(self):\n",
    "        return 0\n",
    "\n",
    "class Rectangle(Shape):\n",
    "    def __init__(self, width, height):\n",
    "        super().__init__(\"rectangle\")\n",
    "        self.width = width\n",
    "        self.height = height\n",
    "\n",
    "    def area(self):\n",
    "        return self.width * self.height\n",
    "\n",
    "class Circle(Shape):\n",
    "    def __init__(self, radius):\n",
    "        super().__init__(\"circle\")\n",
    "        self.radius = radius\n",
    "\n",
    "    def area(self):\n",
    "        return round(3.14159 * self.radius ** 2, 2)\n",
    "\n",
    "shapes = [Rectangle(4, 3), Circle(2), Rectangle(5, 5)]\n",
    "for shape in shapes:\n",
    "    print(shape.name, shape.area())\n",
    "\n",
    "print(\"Total:\", sum(shape.area() for shape in shapes))"
   ],
   "id": "t07-042"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Adding a new shape later (a triangle) needs no change in the loop. That is the power of polymorphism.\n",
    "\n",
    "### 6.3 Without polymorphism\n",
    "\n",
    "The same program without it needs an `if` for every kind, and every new kind means changing this code:"
   ],
   "id": "t07-043"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "shapes = [(\"rectangle\", 4, 3), (\"circle\", 2, 0)]\n",
    "for kind, a, b in shapes:\n",
    "    if kind == \"rectangle\":\n",
    "        print(kind, a * b)\n",
    "    elif kind == \"circle\":\n",
    "        print(kind, round(3.14159 * a ** 2, 2))"
   ],
   "id": "t07-044"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 6.4 Python's own polymorphism\n",
    "\n",
    "You have used it since the first lesson. `len()` and `+` work on different types, and each type does it in its own way:"
   ],
   "id": "t07-045"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(len(\"hello\"))\n",
    "print(len([1, 2, 3]))\n",
    "print(len({\"a\": 1, \"b\": 2}))\n",
    "\n",
    "print(2 + 3)\n",
    "print(\"2\" + \"3\")\n",
    "print([2] + [3])"
   ],
   "id": "t07-046"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 6.5 The four ideas together\n",
    "\n",
    "| Idea | In plain words | In Python |\n",
    "| --- | --- | --- |\n",
    "| Encapsulation | keep data and methods together, protect the data | a class, `self._balance`, methods that check |\n",
    "| Abstraction | a simple method hides the steps | `make_coffee()` calls `_heat_water()`, `_grind_beans()`, `_pour()` |\n",
    "| Inheritance | a child class gets everything from its parent | `class Dog(Animal):`, `super().__init__(...)` |\n",
    "| Polymorphism | the same method name, a different result per class | `for shape in shapes: shape.area()` |\n",
    "\n",
    "One small program with all four:\n",
    "\n",
    "Change it and run: add a third person, `Manager(\"Leyla\", 2000, 0)`."
   ],
   "id": "t07-047"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Employee:\n",
    "    def __init__(self, name, salary):\n",
    "        self.name = name\n",
    "        self._salary = salary\n",
    "\n",
    "    def pay(self):\n",
    "        return self._salary\n",
    "\n",
    "    def describe(self):\n",
    "        return f\"{self.name} earns {self.pay()}\"\n",
    "\n",
    "class Manager(Employee):\n",
    "    def __init__(self, name, salary, bonus):\n",
    "        super().__init__(name, salary)\n",
    "        self._bonus = bonus\n",
    "\n",
    "    def pay(self):\n",
    "        return self._salary + self._bonus\n",
    "\n",
    "staff = [Employee(\"Aylin\", 1000), Manager(\"Murad\", 1500, 400)]\n",
    "for person in staff:\n",
    "    print(person.describe())"
   ],
   "id": "t07-048"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- Encapsulation: the salary is kept inside the object, as `_salary`.\n",
    "- Abstraction: `describe()` gives a ready sentence. The caller does not calculate anything.\n",
    "- Inheritance: `Manager` is an `Employee` and reuses its `__init__` and `describe`.\n",
    "- Polymorphism: `pay()` gives a different result for a manager, and `describe()` uses the right one.\n",
    "\n",
    "### 6.6 When should I write a class?\n",
    "\n",
    "- Use a class when several pieces of data belong together and there are actions on them (an account, a student, a product).\n",
    "- A dictionary is enough for simple data without actions.\n",
    "- A function is enough for one calculation.\n",
    "\n",
    "## 7. Modules and packages\n",
    "\n",
    "### 7.1 What is a module?\n",
    "\n",
    "A module is a file with Python code (functions, classes, values) that you can use in another program. Python comes with many ready modules. This collection is called the standard library.\n",
    "\n",
    "Real-life picture: a toolbox. You do not make a hammer each time you need one. You open the toolbox and take it.\n",
    "\n",
    "### 7.2 `import`\n",
    "\n",
    "Change it and run: print `math.sqrt(2)` and `math.pow(2, 10)`."
   ],
   "id": "t07-049"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import math\n",
    "\n",
    "print(math.sqrt(16))\n",
    "print(math.pi)\n",
    "print(math.floor(3.7), math.ceil(3.2))"
   ],
   "id": "t07-050"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`import math` loads the module. Its functions are used with the module name and a dot: `math.sqrt`.\n",
    "\n",
    "### 7.3 `from ... import`\n",
    "\n",
    "Import only the names you need, and use them without the module name:\n",
    "\n",
    "Change it and run: import `floor` too and print `floor(9.99)`."
   ],
   "id": "t07-051"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from math import sqrt, pi\n",
    "\n",
    "print(sqrt(25))\n",
    "print(round(pi, 2))"
   ],
   "id": "t07-052"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 7.4 `as`: a shorter name\n",
    "\n",
    "Change it and run: add the grade 100 to the list."
   ],
   "id": "t07-053"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import statistics as stats\n",
    "\n",
    "grades = [85, 92, 78, 60]\n",
    "print(stats.mean(grades))\n",
    "print(stats.median(grades))"
   ],
   "id": "t07-054"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "| Form | How you use it | Good for |\n",
    "| --- | --- | --- |\n",
    "| `import math` | `math.sqrt(16)` | the usual way: it is clear where `sqrt` comes from |\n",
    "| `from math import sqrt` | `sqrt(16)` | one or two names that you use often |\n",
    "| `import statistics as stats` | `stats.mean(...)` | long module names |\n",
    "| `from math import *` | `sqrt(16)` | avoid it: you no longer see where a name comes from |\n",
    "\n",
    "### 7.5 Some useful modules of the standard library\n",
    "\n",
    "| Module | What it gives | Example |\n",
    "| --- | --- | --- |\n",
    "| `math` | mathematical functions | `math.sqrt(16)` |\n",
    "| `random` | random numbers and choices | `random.randint(1, 6)` |\n",
    "| `statistics` | mean, median and more | `statistics.mean([1, 2, 3])` |\n",
    "| `datetime` | dates and times | `datetime.date(2026, 10, 3)` |\n",
    "\n",
    "Change it and run: use your own date of birth."
   ],
   "id": "t07-055"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import datetime\n",
    "\n",
    "day = datetime.date(2026, 10, 3)\n",
    "print(day)\n",
    "print(day.year, day.month, day.day)\n",
    "print(day.strftime(\"%d.%m.%Y\"))"
   ],
   "id": "t07-056"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`random` gives a different result each time, so its output is not shown here:\n",
    "\n",
    "```python\n",
    "import random\n",
    "\n",
    "print(random.randint(1, 6))\n",
    "print(random.choice([\"red\", \"green\", \"blue\"]))\n",
    "```\n",
    "\n",
    "Notice that `datetime.date(2026, 10, 3)` creates an object of the class `date`, and `day.year` is an attribute. Modules are full of classes.\n",
    "\n",
    "### 7.6 A module that does not exist\n",
    "\n",
    "```python\n",
    "import maths\n",
    "```\n",
    "\n",
    "```\n",
    "ModuleNotFoundError: No module named 'maths'\n",
    "```\n",
    "\n",
    "### 7.7 Your own module\n",
    "\n",
    "Any `.py` file is a module. Suppose you save this as `shapes.py`:\n",
    "\n",
    "```python\n",
    "# shapes.py\n",
    "def rectangle_area(width, height):\n",
    "    return width * height\n",
    "\n",
    "class Circle:\n",
    "    def __init__(self, radius):\n",
    "        self.radius = radius\n",
    "\n",
    "    def area(self):\n",
    "        return 3.14159 * self.radius ** 2\n",
    "```\n",
    "\n",
    "Another file in the same folder can use it:\n",
    "\n",
    "```python\n",
    "# main.py\n",
    "import shapes\n",
    "\n",
    "print(shapes.rectangle_area(4, 3))\n",
    "circle = shapes.Circle(2)\n",
    "print(circle.area())\n",
    "```\n",
    "\n",
    "This is how big programs are organised: related functions and classes live in their own module.\n",
    "\n",
    "### 7.8 Packages\n",
    "\n",
    "A package is a folder of modules. Big libraries are packages.\n",
    "\n",
    "```\n",
    "school/\n",
    "    students.py\n",
    "    grades.py\n",
    "    reports.py\n",
    "```\n",
    "\n",
    "```python\n",
    "from school import grades\n",
    "from school.students import Student\n",
    "```\n",
    "\n",
    "### 7.9 Packages made by other people\n",
    "\n",
    "Thousands of packages are not part of Python itself. You install them once, and then import them like any module. In a terminal or in Anaconda Prompt:\n",
    "\n",
    "```\n",
    "pip install numpy\n",
    "```\n",
    "\n",
    "or, with Anaconda:\n",
    "\n",
    "```\n",
    "conda install numpy\n",
    "```\n",
    "\n",
    "Then in your program:\n",
    "\n",
    "```python\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "```\n",
    "\n",
    "`np` and `pd` are the short names everybody uses. The rest of this course is built on such packages: NumPy, pandas, Matplotlib and scikit-learn.\n",
    "\n",
    "| Word | Meaning | Example |\n",
    "| --- | --- | --- |\n",
    "| Module | one `.py` file | `math`, your `shapes.py` |\n",
    "| Package | a folder of modules | `numpy`, `pandas` |\n",
    "| Standard library | the modules that come with Python | `math`, `random`, `datetime` |\n",
    "| `pip` / `conda` | tools that install packages | `pip install numpy` |\n",
    "\n",
    "## 8. Common mistakes\n",
    "\n",
    "The red text is the real message Python shows. Where there is no message, the program runs but does the wrong thing: the comment shows what it prints.\n",
    "\n",
    "| Mistake | What happens | Fix |\n",
    "| --- | --- | --- |\n",
    "| Forgetting `self` in a method definition | `TypeError` when the method is called | the first parameter of every method is `self` |\n",
    "| Forgetting `self.` when using an attribute | `NameError`, or the value is lost | `self.name`, not `name` |\n",
    "| Writing `__init__` with one underscore, or `init` | the method is never run | two underscores on each side |\n",
    "| Forgetting the parentheses when creating an object | you get the class, not an object | `rex = Dog(\"Rex\")` |\n",
    "| Forgetting an argument of `__init__` | `TypeError` | pass every argument |\n",
    "| Forgetting `super().__init__(...)` in a child | the parent's attributes do not exist | call it first in the child's `__init__` |\n",
    "| Changing protected data directly | wrong values (a negative balance) | use the methods |\n",
    "| Using a method without parentheses | you get the method, not its result | `room.area()` |\n",
    "| A wrong module name | `ModuleNotFoundError` | check the spelling, or install the package |\n",
    "| Naming your file like a module (`math.py`, `random.py`) | your file is imported instead of the real module | choose another file name |\n",
    "\n",
    "Forgetting `self` in a method definition:\n",
    "\n",
    "```python\n",
    "class Dog:\n",
    "    def bark():\n",
    "        print(\"Woof!\")\n",
    "\n",
    "rex = Dog()\n",
    "rex.bark()\n",
    "```\n",
    "\n",
    "```\n",
    "TypeError: Dog.bark() takes 0 positional arguments but 1 was given\n",
    "```\n",
    "\n",
    "Python passes the object as the first argument, but `bark` has no parameter to receive it.\n",
    "\n",
    "Forgetting `self.` when storing an attribute:\n",
    "\n",
    "```python\n",
    "class Dog:\n",
    "    def __init__(self, name):\n",
    "        name = name\n",
    "\n",
    "rex = Dog(\"Rex\")\n",
    "print(rex.name)\n",
    "```\n",
    "\n",
    "```\n",
    "AttributeError: 'Dog' object has no attribute 'name'\n",
    "```\n",
    "\n",
    "Forgetting `super().__init__(...)`:\n",
    "\n",
    "```python\n",
    "class Person:\n",
    "    def __init__(self, name):\n",
    "        self.name = name\n",
    "\n",
    "class Student(Person):\n",
    "    def __init__(self, name, grade):\n",
    "        self.grade = grade\n",
    "\n",
    "aylin = Student(\"Aylin\", 85)\n",
    "print(aylin.name)\n",
    "```\n",
    "\n",
    "```\n",
    "AttributeError: 'Student' object has no attribute 'name'\n",
    "```\n",
    "\n",
    "## 9. Solved problems (easy to medium-hard)\n",
    "\n",
    "Every example was run, and the outputs are real.\n",
    "\n",
    "### 9.1 Level 1: Easy\n",
    "\n",
    "Problem 1. A class with two attributes"
   ],
   "id": "t07-057"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Book:\n",
    "    def __init__(self, title, pages):\n",
    "        self.title = title\n",
    "        self.pages = pages\n",
    "\n",
    "book = Book(\"Python Basics\", 320)\n",
    "print(book.title)\n",
    "print(book.pages)"
   ],
   "id": "t07-058"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 2. A method that uses the attributes\n",
    "\n",
    "Change it and run: create a square room, 4 by 4."
   ],
   "id": "t07-059"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Rectangle:\n",
    "    def __init__(self, width, height):\n",
    "        self.width = width\n",
    "        self.height = height\n",
    "\n",
    "    def area(self):\n",
    "        return self.width * self.height\n",
    "\n",
    "    def perimeter(self):\n",
    "        return 2 * (self.width + self.height)\n",
    "\n",
    "room = Rectangle(5, 3)\n",
    "print(room.area())\n",
    "print(room.perimeter())"
   ],
   "id": "t07-060"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 3. A method that changes the object\n",
    "\n",
    "Change it and run: call `increase()` two more times."
   ],
   "id": "t07-061"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Counter:\n",
    "    def __init__(self):\n",
    "        self.value = 0\n",
    "\n",
    "    def increase(self):\n",
    "        self.value = self.value + 1\n",
    "\n",
    "counter = Counter()\n",
    "counter.increase()\n",
    "counter.increase()\n",
    "counter.increase()\n",
    "print(counter.value)"
   ],
   "id": "t07-062"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: the object remembers its value between the calls. A plain function cannot do that.\n",
    "\n",
    "Problem 4. Printing an object"
   ],
   "id": "t07-063"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Product:\n",
    "    def __init__(self, name, price):\n",
    "        self.name = name\n",
    "        self.price = price\n",
    "\n",
    "    def __str__(self):\n",
    "        return f\"{self.name}: {self.price} AZN\"\n",
    "\n",
    "print(Product(\"Notebook\", 4.5))\n",
    "print(Product(\"Pen\", 1.2))"
   ],
   "id": "t07-064"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 5. Using a module"
   ],
   "id": "t07-065"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import math\n",
    "\n",
    "radius = 3\n",
    "print(round(math.pi * radius ** 2, 2))\n",
    "print(math.sqrt(144))\n",
    "print(math.factorial(5))"
   ],
   "id": "t07-066"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 9.2 Level 2: Medium\n",
    "\n",
    "Problem 6. A protected age (encapsulation)\n",
    "\n",
    "Change it and run: try `aylin.set_age(200)`."
   ],
   "id": "t07-067"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Person:\n",
    "    def __init__(self, name, age):\n",
    "        self.name = name\n",
    "        self._age = 0\n",
    "        self.set_age(age)\n",
    "\n",
    "    def set_age(self, age):\n",
    "        if age < 0 or age > 120:\n",
    "            raise ValueError(\"age must be between 0 and 120\")\n",
    "        self._age = age\n",
    "\n",
    "    def get_age(self):\n",
    "        return self._age\n",
    "\n",
    "aylin = Person(\"Aylin\", 20)\n",
    "print(aylin.get_age())\n",
    "try:\n",
    "    aylin.set_age(-5)\n",
    "except ValueError as error:\n",
    "    print(\"Problem:\", error)\n",
    "print(aylin.get_age())"
   ],
   "id": "t07-068"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: every change of the age goes through `set_age`, which checks it. The wrong value never reaches the object.\n",
    "\n",
    "Problem 7. A simple method that hides the steps (abstraction)"
   ],
   "id": "t07-069"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Report:\n",
    "    def __init__(self, grades):\n",
    "        self._grades = grades\n",
    "\n",
    "    def _average(self):\n",
    "        return sum(self._grades) / len(self._grades)\n",
    "\n",
    "    def _best(self):\n",
    "        return max(self._grades)\n",
    "\n",
    "    def summary(self):\n",
    "        return f\"Average: {self._average()}, best: {self._best()}\"\n",
    "\n",
    "report = Report([85, 92, 78, 65])\n",
    "print(report.summary())"
   ],
   "id": "t07-070"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: the user calls one method, `summary()`. How the average and the best grade are found is an internal detail.\n",
    "\n",
    "Problem 8. A child class (inheritance)\n",
    "\n",
    "Change it and run: print `bus.wheels`."
   ],
   "id": "t07-071"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Vehicle:\n",
    "    def __init__(self, brand, wheels):\n",
    "        self.brand = brand\n",
    "        self.wheels = wheels\n",
    "\n",
    "    def describe(self):\n",
    "        return f\"{self.brand} with {self.wheels} wheels\"\n",
    "\n",
    "class Bus(Vehicle):\n",
    "    def __init__(self, brand, seats):\n",
    "        super().__init__(brand, 6)\n",
    "        self.seats = seats\n",
    "\n",
    "bus = Bus(\"Isuzu\", 40)\n",
    "print(bus.describe())\n",
    "print(bus.seats)"
   ],
   "id": "t07-072"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: a bus is a vehicle. `describe` is written once, in `Vehicle`.\n",
    "\n",
    "Problem 9. The same method in different classes (polymorphism)"
   ],
   "id": "t07-073"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Email:\n",
    "    def send(self, text):\n",
    "        return f\"Email: {text}\"\n",
    "\n",
    "class Sms:\n",
    "    def send(self, text):\n",
    "        return f\"SMS: {text[:10]}\"\n",
    "\n",
    "for channel in [Email(), Sms()]:\n",
    "    print(channel.send(\"Your lesson starts at 19:00\"))"
   ],
   "id": "t07-074"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 10. Objects in a list"
   ],
   "id": "t07-075"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Student:\n",
    "    def __init__(self, name, grade):\n",
    "        self.name = name\n",
    "        self.grade = grade\n",
    "\n",
    "students = [Student(\"Aylin\", 85), Student(\"Murad\", 42), Student(\"Leyla\", 78)]\n",
    "\n",
    "best = max(students, key=lambda student: student.grade)\n",
    "passed = [student.name for student in students if student.grade >= 50]\n",
    "average = sum(student.grade for student in students) / len(students)\n",
    "\n",
    "print(\"Best:\", best.name)\n",
    "print(\"Passed:\", passed)\n",
    "print(\"Average:\", round(average, 1))"
   ],
   "id": "t07-076"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 9.3 Level 3: Medium-Hard\n",
    "\n",
    "Problem 11. A bank account with a history\n",
    "\n",
    "Change it and run: deposit a negative amount inside the `try`."
   ],
   "id": "t07-077"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "class BankAccount:\n",
    "    def __init__(self, owner):\n",
    "        self.owner = owner\n",
    "        self._balance = 0\n",
    "        self._history = []\n",
    "\n",
    "    def deposit(self, amount):\n",
    "        if amount <= 0:\n",
    "            raise ValueError(\"the amount must be positive\")\n",
    "        self._balance = self._balance + amount\n",
    "        self._history.append(f\"+{amount}\")\n",
    "\n",
    "    def withdraw(self, amount):\n",
    "        if amount > self._balance:\n",
    "            raise ValueError(\"not enough money\")\n",
    "        self._balance = self._balance - amount\n",
    "        self._history.append(f\"-{amount}\")\n",
    "\n",
    "    def __str__(self):\n",
    "        return f\"{self.owner}: {self._balance} ({', '.join(self._history)})\"\n",
    "\n",
    "account = BankAccount(\"Aylin\")\n",
    "account.deposit(100)\n",
    "account.withdraw(30)\n",
    "try:\n",
    "    account.withdraw(500)\n",
    "except ValueError as error:\n",
    "    print(\"Problem:\", error)\n",
    "print(account)"
   ],
   "id": "t07-078"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 12. Employees and managers\n",
    "\n",
    "Change it and run: add `Manager(\"Kamran\", 1800, 250)` to the staff."
   ],
   "id": "t07-079"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Employee:\n",
    "    def __init__(self, name, salary):\n",
    "        self.name = name\n",
    "        self._salary = salary\n",
    "\n",
    "    def pay(self):\n",
    "        return self._salary\n",
    "\n",
    "class Manager(Employee):\n",
    "    def __init__(self, name, salary, bonus):\n",
    "        super().__init__(name, salary)\n",
    "        self._bonus = bonus\n",
    "\n",
    "    def pay(self):\n",
    "        return super().pay() + self._bonus\n",
    "\n",
    "staff = [Employee(\"Aylin\", 1000), Manager(\"Murad\", 1500, 400), Employee(\"Leyla\", 1200)]\n",
    "for person in staff:\n",
    "    print(person.name, person.pay())\n",
    "print(\"Total:\", sum(person.pay() for person in staff))"
   ],
   "id": "t07-080"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: `super().pay()` reuses the parent's calculation, and the manager adds the bonus. The loop treats everyone the same way.\n",
    "\n",
    "Problem 13. A shopping cart made of objects\n",
    "\n",
    "Change it and run: add a third product to the cart."
   ],
   "id": "t07-081"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Product:\n",
    "    def __init__(self, name, price):\n",
    "        self.name = name\n",
    "        self.price = price\n",
    "\n",
    "class Cart:\n",
    "    def __init__(self):\n",
    "        self._items = []\n",
    "\n",
    "    def add(self, product, amount):\n",
    "        self._items.append((product, amount))\n",
    "\n",
    "    def total(self):\n",
    "        return sum(product.price * amount for product, amount in self._items)\n",
    "\n",
    "    def show(self):\n",
    "        for product, amount in self._items:\n",
    "            print(product.name, \"x\", amount)\n",
    "        print(\"Total:\", self.total())\n",
    "\n",
    "cart = Cart()\n",
    "cart.add(Product(\"Notebook\", 4.5), 2)\n",
    "cart.add(Product(\"Pen\", 1.2), 5)\n",
    "cart.show()"
   ],
   "id": "t07-082"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: one object can hold other objects. The cart keeps its list of items inside and offers three simple methods.\n",
    "\n",
    "Problem 14. Shapes with a common parent\n",
    "\n",
    "Change it and run: add a class `Rectangle(Shape)` and put one into the list."
   ],
   "id": "t07-083"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import math\n",
    "\n",
    "class Shape:\n",
    "    def area(self):\n",
    "        raise NotImplementedError(\"each shape must define area()\")\n",
    "\n",
    "    def describe(self):\n",
    "        return f\"{type(self).__name__} with area {round(self.area(), 2)}\"\n",
    "\n",
    "class Square(Shape):\n",
    "    def __init__(self, side):\n",
    "        self.side = side\n",
    "\n",
    "    def area(self):\n",
    "        return self.side ** 2\n",
    "\n",
    "class Circle(Shape):\n",
    "    def __init__(self, radius):\n",
    "        self.radius = radius\n",
    "\n",
    "    def area(self):\n",
    "        return math.pi * self.radius ** 2\n",
    "\n",
    "for shape in [Square(3), Circle(1), Square(1.5)]:\n",
    "    print(shape.describe())"
   ],
   "id": "t07-084"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: `describe` is written once in the parent and calls `area()`, which each child defines in its own way. The parent's `area` raises an error, so a child cannot forget to write its own.\n",
    "\n",
    "Problem 15. A small library system\n",
    "\n",
    "Change it and run: try to borrow `\"Statistics\"`, a book the library does not have, and catch the `KeyError`."
   ],
   "id": "t07-085"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Book:\n",
    "    def __init__(self, title):\n",
    "        self.title = title\n",
    "        self.available = True\n",
    "\n",
    "class Library:\n",
    "    def __init__(self):\n",
    "        self._books = {}\n",
    "\n",
    "    def add(self, title):\n",
    "        self._books[title] = Book(title)\n",
    "\n",
    "    def borrow(self, title):\n",
    "        if title not in self._books:\n",
    "            raise KeyError(title)\n",
    "        book = self._books[title]\n",
    "        if not book.available:\n",
    "            raise ValueError(f\"{title} is already borrowed\")\n",
    "        book.available = False\n",
    "\n",
    "    def available_titles(self):\n",
    "        return [title for title, book in self._books.items() if book.available]\n",
    "\n",
    "library = Library()\n",
    "library.add(\"Python Basics\")\n",
    "library.add(\"Data Science 101\")\n",
    "library.borrow(\"Python Basics\")\n",
    "\n",
    "try:\n",
    "    library.borrow(\"Python Basics\")\n",
    "except ValueError as error:\n",
    "    print(\"Problem:\", error)\n",
    "\n",
    "print(library.available_titles())"
   ],
   "id": "t07-086"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 12. Quick summary\n",
    "\n",
    "| Concept | What it does | Example |\n",
    "| --- | --- | --- |\n",
    "| Class | the plan for a kind of object | `class Dog:` |\n",
    "| Object (instance) | one real thing made from a class | `rex = Dog(\"Rex\", 3)` |\n",
    "| `__init__` | runs when an object is created | `def __init__(self, name):` |\n",
    "| `self` | the object itself | `self.name = name` |\n",
    "| Attribute | data of an object | `rex.name` |\n",
    "| Method | an action of an object | `rex.bark()` |\n",
    "| `__str__` | the text that `print` shows | `def __str__(self):` |\n",
    "| Encapsulation | data and methods together, data protected | `self._balance`, `deposit()` |\n",
    "| Abstraction | a simple method hides the steps | `machine.make_coffee()` |\n",
    "| Inheritance | a child class gets everything from its parent | `class Dog(Animal):` |\n",
    "| `super()` | calls a method of the parent | `super().__init__(name)` |\n",
    "| Polymorphism | the same method name, different behaviour | `for s in shapes: s.area()` |\n",
    "| `import` | loads a module | `import math` |\n",
    "| `from ... import` | loads chosen names | `from math import sqrt` |\n",
    "| `as` | gives a shorter name | `import numpy as np` |\n",
    "| Package | a folder of modules, often installed with `pip` | `pip install numpy` |\n",
    "\n",
    "Golden rules\n",
    "\n",
    "1. A class is the plan, an object is the thing. Class names start with a capital letter.\n",
    "2. The first parameter of every method is `self`, and attributes are written as `self.name`.\n",
    "3. Protect data: start internal attributes with `_` and change them through methods that check the value.\n",
    "4. Give users one simple method, and hide the steps.\n",
    "5. Use inheritance only when \"is a\" is true: a dog is an animal.\n",
    "6. Give the same method name to the same action in different classes. Then one loop can use them all.\n",
    "7. Import what you need, and never name your own file like a module you use.\n",
    "\n",
    "Next: the practice notebook (topic-07-practice.ipynb), then Topic 8: NumPy fundamentals: arrays and indexing."
   ],
   "id": "t07-087"
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
