{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Reflektion" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Reflektion oder Introspektion ist eine Technik,\n", "wo das Programm etwas über sich selbst weiß.\n", "Es kann während des Ausführens Informationen über die Struktur von Datenstrukturen erfahren,\n", "und eventuell diese Strukturen auch dynamisch modifizieren." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Informationen über Datenstrukturen" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Typ" ] }, { "cell_type": "code", "execution_count": 18, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "str" ] }, "execution_count": 18, "metadata": {}, "output_type": "execute_result" } ], "source": [ "type(\"abc\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Instanzen einer Klasse" ] }, { "cell_type": "code", "execution_count": 21, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 21, "metadata": {}, "output_type": "execute_result" } ], "source": [ "isinstance(u\"abc\", str)" ] }, { "cell_type": "code", "execution_count": 22, "metadata": { "collapsed": false }, "outputs": [], "source": [ "l = [1,2,3]\n", "t = (1,2,3)" ] }, { "cell_type": "code", "execution_count": 23, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 23, "metadata": {}, "output_type": "execute_result" } ], "source": [ "isinstance(l, (list, tuple))" ] }, { "cell_type": "code", "execution_count": 24, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 24, "metadata": {}, "output_type": "execute_result" } ], "source": [ "isinstance(t, (list, tuple))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Attribute abfragen" ] }, { "cell_type": "code", "execution_count": 25, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 25, "metadata": {}, "output_type": "execute_result" } ], "source": [ "x = \"abc\"\n", "hasattr(x, \"date\")" ] }, { "cell_type": "code", "execution_count": 26, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 26, "metadata": {}, "output_type": "execute_result" } ], "source": [ "hasattr(x, \"__len__\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Attribut auswählen\n", "Statt der \".\" Notation, geht auch:" ] }, { "cell_type": "code", "execution_count": 27, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "[1, 2, 3]" ] }, "execution_count": 27, "metadata": {}, "output_type": "execute_result" } ], "source": [ "l = [1]\n", "l.append(2)\n", "getattr(l, \"append\")(3)\n", "l" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Attribute auflisten" ] }, { "cell_type": "code", "execution_count": 28, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']\n" ] } ], "source": [ "x = \"abc\"\n", "# nur solche, die nicht mit \"_\" beginnen\n", "print([a for a in dir(x) if not a.startswith(\"_\")])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Callable\n", "Eine Funktion, Konstruktur, etc." ] }, { "cell_type": "code", "execution_count": 29, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 29, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from datetime import datetime\n", "callable(datetime)" ] }, { "cell_type": "code", "execution_count": 30, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 30, "metadata": {}, "output_type": "execute_result" } ], "source": [ "callable(42)" ] }, { "cell_type": "code", "execution_count": 31, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 31, "metadata": {}, "output_type": "execute_result" } ], "source": [ "def f(x):\n", " return 2*x\n", "callable(f)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## inspect\n", "\n", "Die [inspect](https://docs.python.org/2/library/inspect.html) erlaubt, Objekte während der Ausführung genauer zu untersuchen." ] }, { "cell_type": "code", "execution_count": 32, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import inspect" ] }, { "cell_type": "code", "execution_count": 33, "metadata": { "collapsed": false }, "outputs": [], "source": [ "def f2(k, l = \"hello\"):\n", " return l * k" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Code der `f2` Funktion" ] }, { "cell_type": "code", "execution_count": 34, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "def f2(k, l = \"hello\"):\n", " return l * k\n", "\n" ] } ], "source": [ "print(inspect.getsource(f2))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Aufrufspezifikationen für die Funktion `f2`" ] }, { "cell_type": "code", "execution_count": 35, "metadata": { "collapsed": false }, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "/projects/anaconda3/lib/python3.5/site-packages/ipykernel/__main__.py:1: DeprecationWarning: inspect.getargspec() is deprecated, use inspect.signature() instead\n", " if __name__ == '__main__':\n" ] }, { "data": { "text/plain": [ "ArgSpec(args=['k', 'l'], varargs=None, keywords=None, defaults=('hello',))" ] }, "execution_count": 35, "metadata": {}, "output_type": "execute_result" } ], "source": [ "inspect.getargspec(f2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Stack\n", "\n", "Während der Ausführung, kann man auch auf den [Stack des Interpreters](https://docs.python.org/2/library/inspect.html#the-interpreter-stack) zugreifen." ] }, { "cell_type": "code", "execution_count": 36, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Traceback(filename='', lineno=2, function='', code_context=['frame = inspect.currentframe()\\n'], index=0)\n", "Lokale Variable x: 42\n" ] } ], "source": [ "x = 42\n", "frame = inspect.currentframe()\n", "print(inspect.getframeinfo(frame))\n", "print(\"Lokale Variable x: %s\" % frame.f_locals['x'])" ] } ], "metadata": { "kernelspec": { "display_name": "Anaconda (Python 3)", "language": "python", "name": "anaconda3" }, "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.1" } }, "nbformat": 4, "nbformat_minor": 0 }