{ "cells": [ { "cell_type": "markdown", "metadata": { "nbsphinx": "hidden" }, "source": [ "[prev: Introduction aux fonctions](fonction-intro.ipynb) | [home](../index.ipynb) | [next: Les conteneurs de base](data-structures.ipynb)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# *type()* et *help()* : introspection\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- En python, *tout* est objet.\n", "- Le type des objets est fixe.\n", "- Un même nom peut désigner tour à tour des objets de types différents : pas de \"déclaration des variables\".\n", "\n", "Comment s'y retrouver ?" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Qui es-tu ?" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "\n", "\n" ] } ], "source": [ "# type() nous indique le type d'un objet\n", "print(type(2))\n", "print(type(3.14))\n", "print(type('toto'))" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "type(2) == int" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n" ] } ], "source": [ "# Quel est le type de 'int' ?\n", "print(type(int))" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n" ] } ], "source": [ "# Quel est le type de 'type' ?\n", "print(type(type(int)))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Que fais-tu ?" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Plus que le type d'un objet, on s'intéressera à ce qu'il sait faire." ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Help on int object:\n", "\n", "class int(object)\n", " | int([x]) -> integer\n", " | int(x, base=10) -> integer\n", " | \n", " | Convert a number or string to an integer, or return 0 if no arguments\n", " | are given. If x is a number, return x.__int__(). For floating point\n", " | numbers, this truncates towards zero.\n", " | \n", " | If x is not a number or if base is given, then x must be a string,\n", " | bytes, or bytearray instance representing an integer literal in the\n", " | given base. The literal can be preceded by '+' or '-' and be surrounded\n", " | by whitespace. The base defaults to 10. Valid bases are 0 and 2-36.\n", " | Base 0 means to interpret the base from the string as an integer literal.\n", " | >>> int('0b100', base=0)\n", " | 4\n", " | \n", " | Built-in subclasses:\n", " | bool\n", " | \n", " | Methods defined here:\n", " | \n", " | __abs__(self, /)\n", " | abs(self)\n", " | \n", " | __add__(self, value, /)\n", " | Return self+value.\n", " | \n", " | __and__(self, value, /)\n", " | Return self&value.\n", " | \n", " | __bool__(self, /)\n", " | True if self else False\n", " | \n", " | __ceil__(...)\n", " | Ceiling of an Integral returns itself.\n", " | \n", " | __divmod__(self, value, /)\n", " | Return divmod(self, value).\n", " | \n", " | __eq__(self, value, /)\n", " | Return self==value.\n", " | \n", " | __float__(self, /)\n", " | float(self)\n", " | \n", " | __floor__(...)\n", " | Flooring an Integral returns itself.\n", " | \n", " | __floordiv__(self, value, /)\n", " | Return self//value.\n", " | \n", " | __format__(self, format_spec, /)\n", " | Default object formatter.\n", " | \n", " | __ge__(self, value, /)\n", " | Return self>=value.\n", " | \n", " | __getattribute__(self, name, /)\n", " | Return getattr(self, name).\n", " | \n", " | __getnewargs__(self, /)\n", " | \n", " | __gt__(self, value, /)\n", " | Return self>value.\n", " | \n", " | __hash__(self, /)\n", " | Return hash(self).\n", " | \n", " | __index__(self, /)\n", " | Return self converted to an integer, if self is suitable for use as an index into a list.\n", " | \n", " | __int__(self, /)\n", " | int(self)\n", " | \n", " | __invert__(self, /)\n", " | ~self\n", " | \n", " | __le__(self, value, /)\n", " | Return self<=value.\n", " | \n", " | __lshift__(self, value, /)\n", " | Return self<>self.\n", " | \n", " | __rshift__(self, value, /)\n", " | Return self>>value.\n", " | \n", " | __rsub__(self, value, /)\n", " | Return value-self.\n", " | \n", " | __rtruediv__(self, value, /)\n", " | Return value/self.\n", " | \n", " | __rxor__(self, value, /)\n", " | Return value^self.\n", " | \n", " | __sizeof__(self, /)\n", " | Returns size in memory, in bytes.\n", " | \n", " | __sub__(self, value, /)\n", " | Return self-value.\n", " | \n", " | __truediv__(self, value, /)\n", " | Return self/value.\n", " | \n", " | __trunc__(...)\n", " | Truncating an Integral returns itself.\n", " | \n", " | __xor__(self, value, /)\n", " | Return self^value.\n", " | \n", " | as_integer_ratio(self, /)\n", " | Return integer ratio.\n", " | \n", " | Return a pair of integers, whose ratio is exactly equal to the original int\n", " | and with a positive denominator.\n", " | \n", " | >>> (10).as_integer_ratio()\n", " | (10, 1)\n", " | >>> (-10).as_integer_ratio()\n", " | (-10, 1)\n", " | >>> (0).as_integer_ratio()\n", " | (0, 1)\n", " | \n", " | bit_count(self, /)\n", " | Number of ones in the binary representation of the absolute value of self.\n", " | \n", " | Also known as the population count.\n", " | \n", " | >>> bin(13)\n", " | '0b1101'\n", " | >>> (13).bit_count()\n", " | 3\n", " | \n", " | bit_length(self, /)\n", " | Number of bits necessary to represent self in binary.\n", " | \n", " | >>> bin(37)\n", " | '0b100101'\n", " | >>> (37).bit_length()\n", " | 6\n", " | \n", " | conjugate(...)\n", " | Returns self, the complex conjugate of any int.\n", " | \n", " | to_bytes(self, /, length, byteorder, *, signed=False)\n", " | Return an array of bytes representing an integer.\n", " | \n", " | length\n", " | Length of bytes object to use. An OverflowError is raised if the\n", " | integer is not representable with the given number of bytes.\n", " | byteorder\n", " | The byte order used to represent the integer. If byteorder is 'big',\n", " | the most significant byte is at the beginning of the byte array. If\n", " | byteorder is 'little', the most significant byte is at the end of the\n", " | byte array. To request the native byte order of the host system, use\n", " | `sys.byteorder' as the byte order value.\n", " | signed\n", " | Determines whether two's complement is used to represent the integer.\n", " | If signed is False and a negative integer is given, an OverflowError\n", " | is raised.\n", " | \n", " | ----------------------------------------------------------------------\n", " | Class methods defined here:\n", " | \n", " | from_bytes(bytes, byteorder, *, signed=False) from builtins.type\n", " | Return the integer represented by the given array of bytes.\n", " | \n", " | bytes\n", " | Holds the array of bytes to convert. The argument must either\n", " | support the buffer protocol or be an iterable object producing bytes.\n", " | Bytes and bytearray are examples of built-in objects that support the\n", " | buffer protocol.\n", " | byteorder\n", " | The byte order used to represent the integer. If byteorder is 'big',\n", " | the most significant byte is at the beginning of the byte array. If\n", " | byteorder is 'little', the most significant byte is at the end of the\n", " | byte array. To request the native byte order of the host system, use\n", " | `sys.byteorder' as the byte order value.\n", " | signed\n", " | Indicates whether two's complement is used to represent the integer.\n", " | \n", " | ----------------------------------------------------------------------\n", " | Static methods defined here:\n", " | \n", " | __new__(*args, **kwargs) from builtins.type\n", " | Create and return a new object. See help(type) for accurate signature.\n", " | \n", " | ----------------------------------------------------------------------\n", " | Data descriptors defined here:\n", " | \n", " | denominator\n", " | the denominator of a rational number in lowest terms\n", " | \n", " | imag\n", " | the imaginary part of a complex number\n", " | \n", " | numerator\n", " | the numerator of a rational number in lowest terms\n", " | \n", " | real\n", " | the real part of a complex number\n", "\n" ] } ], "source": [ "help(2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "De même pour les fonctions." ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [], "source": [ "def add(x, y):\n", " \"additionne x et y\"\n", " result = x + y\n", " return result" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n" ] } ], "source": [ "print(type(add))" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Help on function add in module __main__:\n", "\n", "add(x, y)\n", " additionne x et y\n", "\n" ] } ], "source": [ "help(add)" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Help on built-in function max in module builtins:\n", "\n", "max(...)\n", " max(iterable, *[, default=obj, key=func]) -> value\n", " max(arg1, arg2, *args, *[, key=func]) -> value\n", " \n", " With a single iterable argument, return its biggest item. The\n", " default keyword-only argument specifies an object to return if\n", " the provided iterable is empty.\n", " With two or more arguments, return the largest argument.\n", "\n" ] } ], "source": [ "# max() est une fonction 'builtin'\n", "help(max)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Qui est là ?" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Pour une information plus 'brute' sur l'objet : `dir()` et `vars()`" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['__abs__',\n", " '__add__',\n", " '__and__',\n", " '__bool__',\n", " '__ceil__',\n", " '__class__',\n", " '__delattr__',\n", " '__dir__',\n", " '__divmod__',\n", " '__doc__',\n", " '__eq__',\n", " '__float__',\n", " '__floor__',\n", " '__floordiv__',\n", " '__format__',\n", " '__ge__',\n", " '__getattribute__',\n", " '__getnewargs__',\n", " '__gt__',\n", " '__hash__',\n", " '__index__',\n", " '__init__',\n", " '__init_subclass__',\n", " '__int__',\n", " '__invert__',\n", " '__le__',\n", " '__lshift__',\n", " '__lt__',\n", " '__mod__',\n", " '__mul__',\n", " '__ne__',\n", " '__neg__',\n", " '__new__',\n", " '__or__',\n", " '__pos__',\n", " '__pow__',\n", " '__radd__',\n", " '__rand__',\n", " '__rdivmod__',\n", " '__reduce__',\n", " '__reduce_ex__',\n", " '__repr__',\n", " '__rfloordiv__',\n", " '__rlshift__',\n", " '__rmod__',\n", " '__rmul__',\n", " '__ror__',\n", " '__round__',\n", " '__rpow__',\n", " '__rrshift__',\n", " '__rshift__',\n", " '__rsub__',\n", " '__rtruediv__',\n", " '__rxor__',\n", " '__setattr__',\n", " '__sizeof__',\n", " '__str__',\n", " '__sub__',\n", " '__subclasshook__',\n", " '__truediv__',\n", " '__trunc__',\n", " '__xor__',\n", " 'as_integer_ratio',\n", " 'bit_count',\n", " 'bit_length',\n", " 'conjugate',\n", " 'denominator',\n", " 'from_bytes',\n", " 'imag',\n", " 'numerator',\n", " 'real',\n", " 'to_bytes']" ] }, "execution_count": 10, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# une list de string regroupant tous les noms (attribut/méthode) accessibles dans la classe int\n", "dir(int)" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "mappingproxy({'__new__': ,\n", " '__repr__': ,\n", " '__hash__': ,\n", " '__getattribute__': ,\n", " '__lt__': ,\n", " '__le__': ,\n", " '__eq__': ,\n", " '__ne__': ,\n", " '__gt__': ,\n", " '__ge__': ,\n", " '__add__': ,\n", " '__radd__': ,\n", " '__sub__': ,\n", " '__rsub__': ,\n", " '__mul__': ,\n", " '__rmul__': ,\n", " '__mod__': ,\n", " '__rmod__': ,\n", " '__divmod__': ,\n", " '__rdivmod__': ,\n", " '__pow__': ,\n", " '__rpow__': ,\n", " '__neg__': ,\n", " '__pos__': ,\n", " '__abs__': ,\n", " '__bool__': ,\n", " '__invert__': ,\n", " '__lshift__': ,\n", " '__rlshift__': ,\n", " '__rshift__': ,\n", " '__rrshift__': ,\n", " '__and__': ,\n", " '__rand__': ,\n", " '__xor__': ,\n", " '__rxor__': ,\n", " '__or__': ,\n", " '__ror__': ,\n", " '__int__': ,\n", " '__float__': ,\n", " '__floordiv__': ,\n", " '__rfloordiv__': ,\n", " '__truediv__': ,\n", " '__rtruediv__': ,\n", " '__index__': ,\n", " 'conjugate': ,\n", " 'bit_length': ,\n", " 'bit_count': ,\n", " 'to_bytes': ,\n", " 'from_bytes': ,\n", " 'as_integer_ratio': ,\n", " '__trunc__': ,\n", " '__floor__': ,\n", " '__ceil__': ,\n", " '__round__': ,\n", " '__getnewargs__': ,\n", " '__format__': ,\n", " '__sizeof__': ,\n", " 'real': ,\n", " 'imag': ,\n", " 'numerator': ,\n", " 'denominator': ,\n", " '__doc__': \"int([x]) -> integer\\nint(x, base=10) -> integer\\n\\nConvert a number or string to an integer, or return 0 if no arguments\\nare given. If x is a number, return x.__int__(). For floating point\\nnumbers, this truncates towards zero.\\n\\nIf x is not a number or if base is given, then x must be a string,\\nbytes, or bytearray instance representing an integer literal in the\\ngiven base. The literal can be preceded by '+' or '-' and be surrounded\\nby whitespace. The base defaults to 10. Valid bases are 0 and 2-36.\\nBase 0 means to interpret the base from the string as an integer literal.\\n>>> int('0b100', base=0)\\n4\"})" ] }, "execution_count": 11, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# un dict de string:valeur regroupant tous les noms (attribut/méthode) accessibles dans la classe int et leurs valeurs\n", "vars(int)" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Help on built-in function dir in module builtins:\n", "\n", "dir(...)\n", " dir([object]) -> list of strings\n", " \n", " If called without an argument, return the names in the current scope.\n", " Else, return an alphabetized list of names comprising (some of) the attributes\n", " of the given object, and of attributes reachable from it.\n", " If the object supplies a method named __dir__, it will be used; otherwise\n", " the default dir() logic is used and returns:\n", " for a module object: the module's attributes.\n", " for a class object: its attributes, and recursively the attributes\n", " of its bases.\n", " for any other object: its attributes, its class's attributes, and\n", " recursively the attributes of its class's base classes.\n", "\n" ] } ], "source": [ "# dir() et vars() sans argument sont aussi très utiles\n", "help(dir)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Exercice" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "*`max()` est fournie par défaut (builtin), il y en a d'autres.*\n", "\n", "A quoi sert la seule fonction 'builtin' qui commence 'b' et finie par 'n' ?\n", "\n", "Indices :\n", "\n", "1. `dir()` nous donne les noms utilisé actuellement\n", "2. `help(max)` nous dit d'où vient cette fonction\n", "3. `dir([truc])` nous donne le *contenu* de `truc` " ] } ], "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.12" } }, "nbformat": 4, "nbformat_minor": 4 }