Python — Les fonctions : définition, valeurs par défaut et fonctions d’ordre supérieur
utiliser help()
Vous avez déjà vu des fonctions comme print et abs. Mais Python en propose beaucoup d’autres, et la fonction la plus utile pour les découvrir est help().
help(round)
Sortie (extrait)
Help on built-in function round in module builtins:
round(number, ndigits=None) Round a number to a given precision in decimal digits.
help(round(-2.01)) # ❌ Passe un int à help(), pas la fonction round
Sortie (extrait)
Help on int object: class int(object) | int([x]) -> integer | int(x, base=10) -> integer |
| Convert a number or string to an integer, or return 0 if no arguments | are given. If x is a number, return x.int(). For floating point | numbers, this truncates towards zero. |
| If x is not a number or if base is given, then x must be a string, | bytes, or bytearray instance representing an integer literal in the | given base. The literal can be preceded by '+' or '-' and be surrounded | by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. | Base 0 means to interpret the base from the string as an integer literal. | >>> int('0b100', base=0) | 4 |
| Methods defined here: |
| abs(self, /) | abs(self) |
| add(self, value, /) | Return self+value. |
| and(self, value, /) | Return self&value. |
| bool(self, /) | self != 0 |
| ceil(...) | Ceiling of an Integral returns itself. |
| divmod(self, value, /) | Return divmod(self, value). |
| eq(self, value, /) | Return self==value. |
| float(self, /) | float(self) |
| floor(...) | Flooring an Integral returns itself. |
| floordiv(self, value, /) | Return self//value. |
| format(self, format_spec, /) | Default object formatter. |
| ge(self, value, /) | Return self>=value. |
| getattribute(self, name, /) | Return getattr(self, name). |
| getnewargs(self, /) |
| gt(self, value, /) | Return self>value. |
| hash(self, /) | Return hash(self). |
| index(self, /) | Return self converted to an integer, if self is suitable for use as an index into a list. |
| int(self, /) | int(self) |
| invert(self, /) | ~self |
| le(self, value, /) | Returnself<=value. |
| lshift(self, value, /) | Returnself<<value. |
| lt(self, value, /) | Returnself<value. |
| mod(self, value, /) | Return self%value. |
| mul(self, value, /) | Return selfvalue. |
| ne(self, value, /) | Return self!=value. |
| neg(self, /) | -self |
| or(self, value, /) | Return self|value. |
| pos(self, /) | +self |
| pow(self, value, mod=None, /) | Return pow(self, value, mod). |
| radd(self, value, /) | Return value+self. |
| rand(self, value, /) | Return value&self. |
| rdivmod(self, value, /) | Return divmod(value, self). |
| repr(self, /) | Return repr(self). |
| rfloordiv(self, value, /) | Return value//self. |
| rlshift(self, value, /) | Return value<<self. |
| rmod(self, value, /) | Return value%self. |
| rmul(self, value, /) | Return valueself. |
| ror(self, value, /) | Return value|self. |
| round(...) | Rounding an Integral returns itself. | Rounding with an ndigits argument also returns an integer. |
| rpow(self, value, mod=None, /) | Return pow(value, self, mod). |
| rrshift(self, value, /) | Return value>>self. |
| rshift(self, value, /) | Return self>>value. |
| rsub(self, value, /) | Return value-self. |
| rtruediv(self, value, /) | Return value/self. |
| rxor(self, value, /) | Return value^self. |
| sizeof(self, /) | Returns size in memory, in bytes. |
| str(self, /) | Return str(self). |
| sub(self, value, /) | Return self-value. |
| truediv(self, value, /) | Return self/value. |
| trunc(...) | Truncating an Integral returns itself. |
| xor(self, value, /) | Return self^value. |
| bit_length(self, /) | Number of bits necessary to represent self in binary. |
| >>> bin(37) | '0b100101' | >>> (37).bit_length() | 6 |
| conjugate(...) | Returns self, the complex conjugate of any int. |
| to_bytes(self, /, length, byteorder, *, signed=False) | Return an array of bytes representing an integer. |
| length | Length of bytes object to use. An OverflowError is raised if the | integer is not representable with the given number of bytes. | byteorder | The byte order used to represent the integer. If byteorder is 'big', | the most significant byte is at the beginning of the byte array. If | byteorder is 'little', the most significant byte is at the end of the | byte array. To request the native byte order of the host system, use | 'sys.byteorder' as the byte order value. | signed | Determines whether two's complement is used to represent the integer. | If signed is False and a negative integer is given, an OverflowError | is raised. |
| ---------------------------------------------------------------------- | Class methods defined here: |
| from_bytes(bytes, byteorder, *, signed=False) from builtins.type | Return the integer represented by the given array of bytes. |
| bytes | Holds the array of bytes to convert. The argument must either | support the buffer protocol or be an iterable object producing bytes. | Bytes and bytearray are examples of built-in objects that support the | buffer protocol. | byteorder | The byte order used to represent the integer. If byteorder is 'big', | the most significant byte is at the beginning of the byte array. If | byteorder is 'little', the most significant byte is at the end of the | byte array. To request the native byte order of the host system, use | 'sys.byteorder' as the byte order value. | signed | Indicates whether two's complement is used to represent the integer. |
| ---------------------------------------------------------------------- | Static methods defined here: |
| new(*args, **kwargs) from builtins.type | Create and return a new object. See help(type) for accurate signature. |
| ---------------------------------------------------------------------- | Data descriptors defined here: |
| denominator | the denominator of a rational number in lowest terms |
| imag | the imaginary part of a complex number |
| numerator | the numerator of a rational number in lowest terms |
| real | the real part of a complex number
Définir des fonctions
Les fonctions intégrées sont pratiques, mais on a vite besoin de définir les nôtres.
def least_difference(a, b, c):
diff1 = abs(a - b)
diff2 = abs(b - c)
diff3 = abs(a - c)
return min(diff1, diff2, diff3)
- Le mot-clé
defintroduit l’entête, le bloc indenté s’exécute lors de l’appel. returnrenvoie une valeur et met fin à la fonction immédiatement.
Essayons :
print(
least_difference(1, 10, 100),
least_difference(1, 10, 10),
least_difference(5, 6, 7), # Python autorise une virgule terminale
)
Sortie
9 0 1
Et ajoutons une docstring : La docstring est une chaîne entre guillemets triples (pouvant s'étendre sur plusieurs lignes) placée immédiatement après l'en-tête d'une fonction. Lorsque nous appelons help() sur une fonction, elle affiche la docstring.
def least_difference(a, b, c):
"""Return the smallest difference between any two numbers
among a, b and c.
>>> least_difference(1, 5, -5)
4
"""
diff1 = abs(a - b)
diff2 = abs(b - c)
diff3 = abs(a - c)
return min(diff1, diff2, diff3)
help(least_difference)
Sortie (extrait)
Help on function least_difference in module main:
least_difference(a, b, c) Return the smallest difference between any two numbers among a, b and c.
least_difference(1, 5, -5) 4
Fonctions sans retour
Que se passe-t-il si on omet return ?
def least_difference(a, b, c):
"""Return the smallest difference between any two numbers among a, b and c."""
diff1 = abs(a - b)
diff2 = abs(b - c)
diff3 = abs(a - c)
min(diff1, diff2, diff3) # aucune valeur renvoyée
print(
least_difference(1, 10, 100),
least_difference(1, 10, 10),
least_difference(5, 6, 7),
)
Sortie
None None None
mystery = print()
print(mystery)
Sortie
None
Arguments par défaut
Comme print, vos fonctions peuvent accepter des arguments optionnels avec des valeurs par défaut.
print(1, 2, 3, sep=' < ')
print(1, 2, 3) # sep vaut par défaut ' '
Sortie
1 < 2 < 3 1 2 3
L'ajout d'arguments facultatifs :
def greet(who="Colin"):
print("Hello,", who)
greet()
greet(who="Kaggle")
greet("world") # l'argument est non ambigu, on peut omettre le nom
Sortie
Hello, Colin Hello, Kaggle Hello, world
Fonctions appliquées à des fonctions
On peut passer une fonction comme argument à une autre fonction (fonction d’ordre supérieur).
def mult_by_five(x):
return 5 * x
def call(fn, arg):
"""Call fn on arg"""
return fn(arg)
def squared_call(fn, arg):
"""Call fn on the result of calling fn on arg"""
return fn(fn(arg))
print(
call(mult_by_five, 1),
squared_call(mult_by_five, 1),
sep='
', # '
' = saut de ligne
)
Sortie
5 25
Autre exemple classique avec max et l’argument key :
def mod_5(x):
"""Return the remainder of x after dividing by 5"""
return x % 5
print(
'Which number is biggest?',
max(100, 51, 14),
'Which number is the biggest modulo 5?',
max(100, 51, 14, key=mod_5),
sep='
',
)
Sortie
Which number is biggest? 100 Which number is the biggest modulo 5? 14
🚀 Conclusion
Vous savez maintenant :
- utiliser
help()pour naviguer dans l’écosystème Python, - définir des fonctions claires avec
def+returnet une bonne docstring, - comprendre les fonctions qui ne renvoient rien (
None) et leurs usages, - écrire des arguments par défaut utiles,
- et manipuler des fonctions d’ordre supérieur via
key=ou en passant des fonctions comme paramètres.