{ "metadata": { "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.8.0" }, "orig_nbformat": 2, "kernelspec": { "name": "python380jvsc74a57bd02334294e789e06453e89f7d5c3c2573679701f9bb5b76ad2158f91cca5c9244c", "display_name": "Python 3.8.0 64-bit ('3.8.0-amd64': pyenv)" } }, "nbformat": 4, "nbformat_minor": 2, "cells": [ { "source": [ " Πληροφορικής και Τηλεπικοινωνιών - Άρτα \n", " Πανεπιστήμιο Ιωαννίνων \n", "\n", " Γκόγκος Χρήστος \n", " http://chgogos.github.io/\n", " Εαρινό εξάμηνο 2020-2021" ], "cell_type": "markdown", "metadata": {} }, { "source": [ "# Υπερφόρτωση τελεστών\n", "\n", "H Python όπως και άλλες γλώσσες (Ada, C++, Ruby) υποστηρίζει υπερφόρτωση τελεστών. Συνεπώς, γνώριμοι τελεστές όπως οι +, _, *, > , < και άλλοι μπορούν να χρησιμοποιηθούν με αντικείμενα κλάσεων που ορίζει ο προγραμματιστής." ], "cell_type": "markdown", "metadata": {} }, { "source": [ "Υλοποίηση πράξεων +, -, * για intervals (https://en.wikipedia.org/wiki/Interval_arithmetic)" ], "cell_type": "markdown", "metadata": {} }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [], "source": [ "class Interval:\n", " def __init__(self, start, end):\n", " self.start = start\n", " self.end = end\n", " \n", " def __str__(self):\n", " return f'({self.start},{self.end})'\n", "\n", " def __add__(self, other):\n", " return Interval(self.start + other.start, self.end + other.end)\n", "\n", " def __sub__(self, other):\n", " return Interval(self.start - other.end, self.end - other.start)\n", "\n", " def __mul__(self, other):\n", " minimum = min([self.start * other.start, self.start * other.end, self.end * other.start, self.end*other.end])\n", " maximum = max([self.start * other.start, self.start * other.end, self.end * other.start, self.end*other.end])\n", " return Interval(minimum, maximum)" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "(5,11)\n(-5,1)\n(-1,5)\n(4,30)\n" ] } ], "source": [ "i1 = Interval(1,5)\n", "i2 = Interval(4,6)\n", "print(i1+i2)\n", "print(i1-i2)\n", "print(i2-i1)\n", "print(i1*i2)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ] }