{ "cells": [ { "cell_type": "markdown", "metadata": { "nbsphinx": "hidden" }, "source": [ "[prev: Listes en intention](list-comprehension.ipynb) | [home](../index.ipynb) | [next: Les générateurs](generator.ipynb)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Fonctions d'ordre supérieur\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "On parle de fonction d'ordre supérieur quand cette fonction :\n", "\n", "- prend une ou plusieurs fonctions en argument\n", "- renvoie une fonction\n", "\n", "Chacune de ces deux propriétés est possible en Python. Il s'agit souvent d'un moyen rendre un code plus modulaire en séparant les logiques internes." ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Bonne appétit\n", "\n", "\n", " OO tomate OO \n", " -- jambon -- \n", " ~~ salade ~~ \n", "<\\__________/>\n" ] } ], "source": [ "# Un exemple de fonctions que l'on peut composer entre elles\n", "\n", "\n", "def pain(func):\n", " def wrapper():\n", " print(\"\")\n", " func()\n", " print(\"<\\__________/>\")\n", " return wrapper\n", " \n", "\n", "def garniture(func):\n", " def wrapper():\n", " print(\" OO tomate OO \")\n", " func()\n", " print(\" ~~ salade ~~ \")\n", " return wrapper\n", "\n", "\n", "def jambon():\n", " print(\" -- jambon -- \")\n", "\n", " \n", "sandwich = pain(garniture(jambon))\n", "\n", "print(\"Bonne appétit\")\n", "print()\n", "sandwich()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Exercices\n", "\n", "Ecrire le corps de la fonction suivante:\n", "``` python\n", "def deriv(func, epsilon=1e-6):\n", " \"\"\" renvoie la fonction dérivée de func\n", " \n", " Le calcul de la dérivée est fait par différence finie:\n", " \n", " f_prime(x) = ( f(x+epsilon) - f(x) ) / epsilon\n", " \n", " \"\"\"\n", " pass\n", "```" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "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.10.9" } }, "nbformat": 4, "nbformat_minor": 1 }