"OOP is a programming paradigm based on the concept of \"objects\", which can contain data, in the form of attributes and code, in the form of methods.\n",
"It's a different way of you thinking about your model/problem. Instead of thinking of a problem as a sequence of commands that need to be executed (procedural, **linear**), you identify single processes/actors and define their attributes and functionalities, so that they can interact with other actors (**nonlinear**).\n",
"\n",
"**Example Problem:\n",
"Create a simple Notepad**\n",
"\n",
"You'll want to be able to add and delete notes. And for each note you want to be able to add, delete and mark (as done) entries. The Notepad should also have a memory of which Note is selected."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Procedural**\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"notes = {}\n",
"selectedNote = None\n",
"\n",
"def addNote(notes, noteName):\n",
" global selectedNote\n",
" selectedNote = noteName\n",
" notes[noteName]={}\n",
" return notes\n",
"\n",
"def deleteNote(notes,noteName):\n",
" global selectedNote\n",
" selectedNote = None\n",
" del notes[noteName]\n",
" return notes\n",
"\n",
"def _noteNameCheck(noteName):\n",
" global selectedNote\n",
" if noteName is None and selectedNote is None:\n",
" raise ValueError(\"Please provide a noteName.\")\n",
"So for simple programs, there is basically not difference between these programming styles. But as soon as it gets more complicated OOP shines, because different parts of the program can be seperated more clearly. Image you want to design a plottling library...\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 4 Pillars of OOP\n",
"- Inheritance (a way to reuse your code)\n",
"- Abstraction (showing only essential features hiding details)\n",
"- Encapsulation (bind data variables and functions together in a class)\n",
"- Polymorphism (create functions with same name and different arguments, redefine functions)\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [],
"source": [
"# Parent class\n",
"class Dog:\n",
" # Class attribute\n",
" species = 'mammal'\n",
"\n",
" # Initializer / Instance attributes\n",
" def __init__(self, name, age):\n",
" self.name = name\n",
" self.age = age\n",
"\n",
" # instance method\n",
" def description(self):\n",
" return \"{} is {} years old\".format(self.name, self.age)\n",