{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Object Oriented Programming II.\n", "OOP II." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
5
is an instance of int
.\n",
"__init__
)\n",
"self
, it is defined inside a method. It is the property of an instance, different instances can have different values.\n",
"self
.\n",
"Exception
class.\n",
"Optionally, you can have other functions or members in the exception class."
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Use correct title\n"
]
}
],
"source": [
"class KnightException(Exception):\n",
" pass\n",
"\n",
"\n",
"try:\n",
" lancelot = Person(\"Lancelot\", \"Mr\")\n",
" x = str(lancelot)\n",
" if x[:3] != \"Sir\":\n",
" raise KnightException(\"Use correct title\")\n",
"except KnightException as s:\n",
" print(s)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Iterable and iterator objects\n",
"As we have seen, the for loop can work on several data types:\n",
"\n",
" for i in L:\n",
" \n",
"`L` can be list, tuple, dict.\n",
"What type of objects can follow for ... in
?\n",
"\n",
"What happens in a for loop?\n",
"* `for ... in OBJ:` calls the `iter(OBJ)` function (the `__iter__(OBJ)` method), which returns an iterator object. If `OBJ` has this method, it means, `OBJ` is iterable.\n",
" * This marks the beginning of the loop.\n",
"* The iterator object has a `__next__()` method which returns the next elements.\n",
" * This goes through the elements\n",
"* or raises a `StopIteration` exception if it ran out of elements.\n",
" * This marks the end of the loop.\n",
"\n",
"An object is **iterable** if one can iterate over, like the *list*, *tuple*. It generates an **iterator** when passed to `iter()` function (or `__iter__()` method). Iterators have `__next__()` method, which returns the next item of the object. Every iterator is also an iterable, but not vicaversa. For example, a *list* is iterable but it is not an iterator. An iterable object needs a method `__iter__()`, which returns an iterator (or a `__getitem__()` method with sequential indexes starting with 0).\n",
"\n",
"These are **special** methods!"
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"