{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Inheritance\n", "- powerful feature that facilitates code reuse mimicking real-world phenomena\n", "- ability to define a new class (child) that is modified version of an existing class (parent)\n", "- can add new methods and properties to a class without modifying the existing class\n", "Limitation(s):
\n", " - can make programs difficult to read\n", " - when method is invoked, it is sometimes not clear where to find its definition esp. in a large project relevant code may be scattered among several modules" ] }, { "cell_type": "code", "execution_count": 10, "metadata": { "collapsed": true }, "outputs": [], "source": [ "class A(object):\n", " def __init__(self):\n", " self.a = 'A'\n", " \n", " def printMe(self):\n", " print(\"A's info: {}\".format(self.a))\n", "\n", "class B:\n", " def __init__(self):\n", " self.b = 'B'\n", " \n", " def printMe(self):\n", " print(\"B's info: {}\".format(self.b))\n", " \n", "class C(B, A): # what happens if you change order?\n", " def __init__(self):\n", " A.__init__(self)\n", " B.__init__(self)\n", " self.c = 'C'\n", " \n", " def printMe(self):\n", " print(\"A's info: {}\".format(self.a))\n", " print(\"B's info: {}\".format(self.b))\n", " print(\"C's info: {}\".format(self.c))\n", " " ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "A's info: A\n", "B's info: B\n", "A's info: A\n", "B's info: B\n", "C's info: C\n" ] } ], "source": [ "obja = A()\n", "obja.printMe()\n", "objb = B()\n", "objb.printMe()\n", "objc = C()\n", "objc.printMe()" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# How can objects of type C can print their c property info" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## abc module - Abstract Base Classes\n", "- allows to define ABCs with abstract methods @abstractmethod decorators" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.6.2" } }, "nbformat": 4, "nbformat_minor": 2 }