{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Classes and Object Oriented Programming" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In an earlier section we discussed *classes* as a way of representing an abstract object, such as a polynomial. The resulting code" ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "collapsed": true }, "outputs": [], "source": [ "class Polynomial(object):\n", " \"\"\"Representing a polynomial.\"\"\"\n", " explanation = \"I am a polynomial\"\n", " \n", " def __init__(self, roots, leading_term):\n", " self.roots = roots\n", " self.leading_term = leading_term\n", " self.order = len(roots)\n", " \n", " def display(self):\n", " string = str(self.leading_term)\n", " for root in self.roots:\n", " if root == 0:\n", " string = string + \"x\"\n", " elif root > 0:\n", " string = string + \"(x - {})\".format(root)\n", " else:\n", " string = string + \"(x + {})\".format(-root)\n", " return string\n", " \n", " def multiply(self, other):\n", " roots = self.roots + other.roots\n", " leading_term = self.leading_term * other.leading_term\n", " return Polynomial(roots, leading_term)\n", " \n", " def explain_to(self, caller):\n", " print(\"Hello, {}. {}.\".format(caller,self.explanation))\n", " print(\"My roots are {}.\".format(self.roots))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "allowed polynomials to be created, displayed, and multiplied together. However, the language is a little cumbersome. We can take advantage of a number of useful features of Python, many of which carry over to other programming languages, to make it easier to use the results." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Remember that the `__init__` function is called when a variable is created. There are a number of special class functions, each of which has two underscores before and after the name. This is another Python *convention* that is effectively a rule: functions surrounded by two underscores have special effects, and will be called by other Python functions internally. So now we can create a variable that represents a specific polynomial by storing its roots and the leading term:" ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hello, Alice. I am a polynomial.\n", "My roots are (1, 2, -3).\n", "Hello, Bob. I am a polynomial.\n", "My roots are (1, 1, 0, -2).\n" ] } ], "source": [ "p_roots = (1, 2, -3)\n", "p_leading_term = 2\n", "p = Polynomial(p_roots, p_leading_term)\n", "p.explain_to(\"Alice\")\n", "q = Polynomial((1,1,0,-2), -1)\n", "q.explain_to(\"Bob\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Another special function that is very useful is `__repr__`. This gives a *representation* of the class. In essence, if you ask Python to `print` a variable, it will print the *string* returned by the `__repr__` function. This was the role played by our `display` method, so we can just change the name of the function, making the `Polynomial` class easier to use. We can use this to create a simple string representation of the polynomial:" ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "collapsed": true }, "outputs": [], "source": [ "class Polynomial(object):\n", " \"\"\"Representing a polynomial.\"\"\"\n", " explanation = \"I am a polynomial\"\n", " \n", " def __init__(self, roots, leading_term):\n", " self.roots = roots\n", " self.leading_term = leading_term\n", " self.order = len(roots)\n", " \n", " def __repr__(self):\n", " string = str(self.leading_term)\n", " for root in self.roots:\n", " if root == 0:\n", " string = string + \"x\"\n", " elif root > 0:\n", " string = string + \"(x - {})\".format(root)\n", " else:\n", " string = string + \"(x + {})\".format(-root)\n", " return string\n", " \n", " def explain_to(self, caller):\n", " print(\"Hello, {}. {}.\".format(caller,self.explanation))\n", " print(\"My roots are {}.\".format(self.roots))" ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "2(x - 1)(x - 2)(x + 3)\n", "-1(x - 1)(x - 1)x(x + 2)\n" ] } ], "source": [ "p = Polynomial(p_roots, p_leading_term)\n", "print(p)\n", "q = Polynomial((1,1,0,-2), -1)\n", "print(q)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The final special function we'll look at (although there are [many more](https://docs.python.org/2/library/operator.html), many of which may be useful) is `__mul__`. This allows Python to *multiply* two variables together. We did this before using the `multiply` method, but by using the `__mul__` method we can multiply together two polynomials using the standard `*` operator. With this we can take the product of two polynomials:" ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "collapsed": true }, "outputs": [], "source": [ "class Polynomial(object):\n", " \"\"\"Representing a polynomial.\"\"\"\n", " explanation = \"I am a polynomial\"\n", " \n", " def __init__(self, roots, leading_term):\n", " self.roots = roots\n", " self.leading_term = leading_term\n", " self.order = len(roots)\n", " \n", " def __repr__(self):\n", " string = str(self.leading_term)\n", " for root in self.roots:\n", " if root == 0:\n", " string = string + \"x\"\n", " elif root > 0:\n", " string = string + \"(x - {})\".format(root)\n", " else:\n", " string = string + \"(x + {})\".format(-root)\n", " return string\n", " \n", " def __mul__(self, other):\n", " roots = self.roots + other.roots\n", " leading_term = self.leading_term * other.leading_term\n", " return Polynomial(roots, leading_term)\n", " \n", " def explain_to(self, caller):\n", " print(\"Hello, {}. {}.\".format(caller,self.explanation))\n", " print(\"My roots are {}.\".format(self.roots))" ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "-2(x - 1)(x - 2)(x + 3)(x - 1)(x - 1)x(x + 2)\n" ] } ], "source": [ "p = Polynomial(p_roots, p_leading_term)\n", "q = Polynomial((1,1,0,-2), -1)\n", "r = p*q\n", "print(r)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We now have a simple class that can represent polynomials and multiply them together, whilst printing out a simple string form representing itself. This can obviously be extended to be much more useful." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Inheritance" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "As we can see above, building a complete class from scratch can be lengthy and tedious. If there is another class that does much of what we want, we can build on top of that. This is the idea behind *inheritance*. \n", "\n", "In the case of the `Polynomial` we declared that it started from the `object` class in the first line defining the class: `class Polynomial(object)`. But we can build on any class, by replacing `object` with something else. Here we will build on the `Polynomial` class that we've started with.\n", "\n", "A *monomial* is a polynomial whose leading term is simply 1. A monomial *is* a polynomial, and could be represented as such. However, we could build a class that knows that the leading term is always 1: there may be cases where we can take advantage of this additional simplicity.\n", "\n", "We build a new monomial class as follows:" ] }, { "cell_type": "code", "execution_count": 7, "metadata": { "collapsed": true }, "outputs": [], "source": [ "class Monomial(Polynomial):\n", " \"\"\"Representing a monomial, which is a polynomial with leading term 1.\"\"\"\n", " \n", " def __init__(self, roots):\n", " self.roots = roots\n", " self.leading_term = 1\n", " self.order = len(roots)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Variables of the `Monomial` class *are* also variables of the `Polynomial` class, so can use all the methods and functions from the `Polynomial` class automatically:" ] }, { "cell_type": "code", "execution_count": 8, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hello, Caroline. I am a polynomial.\n", "My roots are (-1, 4, 9).\n", "1(x + 1)(x - 4)(x - 9)\n" ] } ], "source": [ "m = Monomial((-1, 4, 9))\n", "m.explain_to(\"Caroline\")\n", "print(m)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We note that these functions, methods and variables may not be exactly right, as they are given for the general `Polynomial` class, not by the specific `Monomial` class. If we *redefine* these functions and variables inside the `Monomial` class, they will *override* those defined in the `Polynomial` class. We do not have to override all the functions and variables, just the parts we want to change:" ] }, { "cell_type": "code", "execution_count": 9, "metadata": { "collapsed": true }, "outputs": [], "source": [ "class Monomial(Polynomial):\n", " \"\"\"Representing a monomial, which is a polynomial with leading term 1.\"\"\"\n", " explanation = \"I am a monomial\"\n", " \n", " def __init__(self, roots):\n", " self.roots = roots\n", " self.leading_term = 1\n", " self.order = len(roots)\n", " \n", " def __repr__(self):\n", " string = \"\"\n", " for root in self.roots:\n", " if root == 0:\n", " string = string + \"x\"\n", " elif root > 0:\n", " string = string + \"(x - {})\".format(root)\n", " else:\n", " string = string + \"(x + {})\".format(-root)\n", " return string" ] }, { "cell_type": "code", "execution_count": 10, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hello, Caroline. I am a monomial.\n", "My roots are (-1, 4, 9).\n", "(x + 1)(x - 4)(x - 9)\n" ] } ], "source": [ "m = Monomial((-1, 4, 9))\n", "m.explain_to(\"Caroline\")\n", "print(m)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This has had no effect on the original `Polynomial` class and variables, which can be used as before:" ] }, { "cell_type": "code", "execution_count": 11, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hello, David. I am a polynomial.\n", "My roots are (2, 3).\n", "4(x - 2)(x - 3)\n" ] } ], "source": [ "s = Polynomial((2, 3), 4)\n", "s.explain_to(\"David\")\n", "print(s)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "And, as `Monomial` variables are `Polynomials`, we can multiply them together to get a `Polynomial`:" ] }, { "cell_type": "code", "execution_count": 12, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hello, Erik. I am a polynomial.\n", "My roots are (-1, 4, 9, 2, 3).\n", "4(x + 1)(x - 4)(x - 9)(x - 2)(x - 3)\n" ] } ], "source": [ "t = m*s\n", "t.explain_to(\"Erik\")\n", "print(t)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In fact, we can be a bit smarter than this. Note that the `__init__` function of the `Monomial` class is identical to that of the `Polynomial` class, just with the `leading_term` set explicitly to `1`. Rather than duplicating the code and modifying a single value, we can *call* the `__init__` function of the `Polynomial` class directly. This is because the `Monomial` class is built on the `Polynomial` class, so knows about it. We regenerate the class, but only change the `__init__` function:" ] }, { "cell_type": "code", "execution_count": 13, "metadata": { "collapsed": true }, "outputs": [], "source": [ "class Monomial(Polynomial):\n", " \"\"\"Representing a monomial, which is a polynomial with leading term 1.\"\"\"\n", " explanation = \"I am a monomial\"\n", " \n", " def __init__(self, roots):\n", " Polynomial.__init__(self, roots, 1)\n", " \n", " def __repr__(self):\n", " string = \"\"\n", " for root in self.roots:\n", " if root == 0:\n", " string = string + \"x\"\n", " elif root > 0:\n", " string = string + \"(x - {})\".format(root)\n", " else:\n", " string = string + \"(x + {})\".format(-root)\n", " return string" ] }, { "cell_type": "code", "execution_count": 14, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hello, Fred. I am a monomial.\n", "My roots are (2, -3).\n", "(x - 2)(x + 3)\n" ] } ], "source": [ "v = Monomial((2, -3))\n", "v.explain_to(\"Fred\")\n", "print(v)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We are now being very explicit in saying that a `Monomial` *really is* a `Polynomial` with `leading_term` being `1`. Note, that in this case we are calling the `__init__` function directly, so have to explicitly include the `self` argument." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "By building on top of classes in this fashion, we can build classes that transparently represent the objects that we are interested in. \n", "\n", "Most modern programming languages include some object oriented features. Many (including Python) will have more complex features than are introduced above. However, the key points where\n", "\n", "* a single variable representing an object can be defined,\n", "* methods that are specific to those objects can be defined,\n", "* new classes of object that inherit from and extend other classes can be defined,\n", "\n", "are the essential steps that are common across nearly all." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Exercise: Equivalence classes" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This exercise repeats that from the earlier chapter on classes, but explicitly includes new class methods to make equivalence classes easier to work with.\n", "\n", "An *equivalence class* is a relation that groups objects in a set into related subsets. For example, if we think of the integers modulo $7$, then $1$ is in the same equivalence class as $8$ (and $15$, and $22$, and so on), and $3$ is in the same equivalence class as $10$. We use the tilde $3 \\sim 10$ to denote two objects within the same equivalence class.\n", "\n", "Here, we are going to define the positive integers programmatically from equivalent sequences." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Exercise 1\n", "\n", "Define a Python class `Eqint`. This should be\n", "\n", "1. Initialized by a sequence;\n", "2. Store the sequence;\n", "3. Define its representation (via the `__repr__` function) to be the integer length of the sequence;\n", "4. Redefine equality (via the `__eq__` function) so that two `Eqint`s are equal if their sequences have the same length." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Exercise 2\n", "\n", "Define a `zero` object from the empty list, and three `one` objects, from a single object list, tuple, and string. For example\n", "\n", "```python\n", "one_list = Eqint([1])\n", "one_tuple = Eqint((1,))\n", "one_string = Eqint('1')\n", "```\n", "\n", "Check that none of the `one` objects equal the zero object, but all equal the other `one` objects. Print each object to check that the representation gives the integer length." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Exercise 3\n", "\n", "Redefine the class by including an `__add__` method that combines the two sequences. That is, if `a` and `b` are `Eqint`s then `a+b` should return an `Eqint` defined from combining `a` and `b`s sequences.\n", "\n", "##### Note\n", "\n", "Adding two different *types* of sequences (eg, a list to a tuple) does not work, so it is better to either iterate over the sequences, or to convert to a uniform type before adding." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Exercise 4\n", "\n", "Check your addition function by adding together all your previous `Eqint` objects (which will need re-defining, as the class has been redefined). Print the resulting object to check you get `3`, and also print its internal sequence." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Exercise 5\n", "\n", "We will sketch a construction of the positive integers from *nothing*.\n", "\n", "1. Define an empty list `positive_integers`.\n", "2. Define an `Eqint` called `zero` from the empty list. Append it to `positive_integers`.\n", "3. Define an `Eqint` called `next_integer` from the `Eqint` defined by *a copy of* `positive_integers` (ie, use `Eqint(list(positive_integers))`. Append it to `positive_integers`.\n", "4. Repeat step 3 as often as needed.\n", "\n", "Use this procedure to define the `Eqint` equivalent to $10$. Print it, and its internal sequence, to check." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Exercise: Rational numbers" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Instead of working with floating point numbers, which are not \"exact\", we could work with the rational numbers $\\mathbb{Q}$. A rational number $q \\in \\mathbb{Q}$ is defined by the *numerator* $n$ and *denominator* $d$ as $q = \\frac{n}{d}$, where $n$ and $d$ are *coprime* (ie, have no common divisor other than $1$)." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Exercise 1\n", "\n", "Find a Python function that finds the greatest common divisor (`gcd`) of two numbers. Use this to write a function `normal_form` that takes a numerator and divisor and returns the coprime $n$ and $d$. Test this function on $q = \\frac{3}{2}$, $q = \\frac{15}{3}$, and $q = \\frac{20}{42}$." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Exercise 2\n", "\n", "Define a class `Rational` that uses the `normal_form` function to store the rational number in the appropriate form. Define a `__repr__` function that prints a string that *looks like* $\\frac{n}{d}$ (**hint**: use `len(str(number))` to find the number of digits of an integer, and use `\\n` to start a new line). Test it on the cases above." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Exercise 3\n", "\n", "Overload the `__add__` function so that you can add two rational numbers. Test it on $\\frac{1}{2} + \\frac{1}{3} + \\frac{1}{6} = 1$." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Exercise 4\n", "\n", "Overload the `__mul__` function so that you can multiply two rational numbers. Test it on $\\frac{1}{3} \\times \\frac{15}{2} \\times \\frac{2}{5} = 1$." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Exercise 5\n", "\n", "Overload the [`__rmul__`](https://docs.python.org/2/reference/datamodel.html?highlight=rmul#object.__rmul__) function so that you can multiply a rational by an *integer*. Check that $\\frac{1}{2} \\times 2 = 1$ and $\\frac{1}{2} + (-1) \\times \\frac{1}{2} = 0$. Also overload the `__sub__` function (using previous functions!) so that you can subtract rational numbers and check that $\\frac{1}{2} - \\frac{1}{2} = 0$." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Exercise 6\n", "\n", "Overload the `__float__` function so that `float(q)` returns the floating point approximation to the rational number `q`. Test this on $\\frac{1}{2}, \\frac{1}{3}$, and $\\frac{1}{11}$." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Exercise 7\n", "\n", "Overload the `__lt__` function to compare two rational numbers. Create a list of rational numbers where the denominator is $n = 2, \\dots, 11$ and the numerator is the floored integer $n/2$, ie `n//2`. Use the `sorted` function on that list (which relies on the `__lt__` function)." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Exercise 8\n", "\n", "The [Wallis formula for π](http://mathworld.wolfram.com/WallisFormula.html) is\n", "\n", "$$ \\pi = 2 \\prod_{n=1}^{\\infty} \\frac{ (2 n)^2 }{(2 n - 1) (2 n + 1)}. $$\n", "\n", "We can define a partial product $\\pi_N$ as\n", "\n", "$$ \\pi_N = 2 \\prod_{n=1}^{N} \\frac{ (2 n)^2 }{(2 n - 1) (2 n + 1)}, $$\n", "\n", "each of which are rational numbers.\n", "\n", "Construct a list of the first 20 rational number approximations to $\\pi$ and print them out. Print the sorted list to show that the approximations are always increasing. Then convert them to floating point numbers, construct a `numpy` array, and subtract this array from $\\pi$ to see how accurate they are." ] } ], "metadata": { "kernelspec": { "display_name": "Python [default]", "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.5.2" }, "nbconvert": { "title": "Classes and objects" } }, "nbformat": 4, "nbformat_minor": 0 }