Magic methods¶
Magic methods are predefined names for methods that are going to be used in special conditions. They are surrounded by double underscores.
Here is an example of how to use them:
from random import random
class Fuzzy():
def __init__(self, val): # constructor, will be called when an object is created
self.a = val
def __repr__(self): # explains how to display the object
return "→" + str(self.a)
def __add__(self, other): # defines the addition
if not isinstance(other, self.__class__):
other = self.__class__(other)
return Fuzzy((self.a + other.a) * ( 0.9 + 0.2*random())) # result ± 10 %
def __str__(self): # how to convert to a string
return "#" + str(self.a)
def __int__(self): # how to convert to int
return round(self.a)
x = Fuzzy(3) # use magic method __init__
y = Fuzzy(5)
print(x) # uses magic method __str__ or __repr__ if __str__ is not defined
print(f"{x!r}") # uses magic method __repr__ because of the !r
print(x + y) # uses magic method __add__ --> x.__add__(y)
print(int(x + 2.5)) # uses __int__ to convert
x # Jupyter uses __repr__ to display objects
#3 →3 #7.781959015488265 5
→3
Une liste de méthodes magiques importantes¶
Méthodes pour la classe A
et ses objet a
et b
. On a n
un entier, x
un réel, foo
une liste ou un dictionnaire.
Op | Méthode | Descrption |
---|---|---|
a = A(other) |
__new__(cls, other) |
Création de l'objet |
a = A(other) |
__init__(self, other) |
Fin de la création de l'objet, appelé par __new__ |
del a |
__del__(self) |
Destructeur |
Opérateurs unaire et fonctions
| +a
| __pos__(self)
| Positif unitaire |
| -a
| __neg__(self)
| Négatif unitaire |
| abs(a)
| __abs__(self)
| Valeur absolue |
| ~a
| __invert__(self)
| Négation logique (binary not) |
| round(a, n)
| __round__(self, n)
| Arrondi à n décimales |
| math.floor(a)
| __floor__(self)
| Valeur entière inférieur ou égale |
| math.ceil(a)
| __abs__(self)
| Valeur entière supérieure ou égale |
| math.trunc(a)
| __trunc__(self)
| Valeur entière inférieur ou égale |
Opérateurs binaires
| a + b
| __add__(self, other)
| Addition |
| a - b
| __sub__(self, other)
| Soustraction |
| a * b
| __mul__(self, other)
| Multiplication |
| a / b
| __truediv__(self, other)
| Division |
| a // b
| __floordiv__(self, other)
| Division entière |
| a % b
| __mod__(self, other)
| Modulo |
| a**b
| __pow__(self, other[, modulo])
| Puissance |
| a < b
| __lt__(self, other)
| Strictement inférieur |
| a <= b
| __le__(self, other)
| Inférieur ou égal |
| a == b
| __eq__(self, other)
| Égalité |
| a != b
| __ne__(self, other)
| Différent |
| a > b
| __gt__(self, other)
| Strictement supérieur |
| a >= b
| __ge__(self, other)
| Supérieur ou égal |
Opérateurs avec assignement
| a += b
| __iadd__(self, other)
| Addition |
| a -= b
| __isub__(self, other)
| Soustraction |
| a *= b
| __imul__(self, other)
| Multiplication |
| a /= b
| __itruediv__(self, other)
| Division |
| a //= b
| __ifloordiv__(self, other)
| Division entière |
| a %= b
| __imod__(self, other)
| Modulo |
| a **= b
| __ipow__(self, other[, modulo])
| Puissance |
Conversion
| int(a)
| __int__(self)
| Convertit en entier |
| float(a)
| __float__(self)
| Convertit en réel |
| complex(a)
| __complex__(self)
| Convertit en complexe |
| oct(a)
| __oct__(self)
| Convertit en octal |
| hex(a)
| __hex__(self)
| Convertit en hexdécimal |
| str(a)
| __str__(self)
| Convertit en une chaîne de caractère |
Présentation
| print(a)
| __repr__(self)
| Représentation de l'objet. Si absent, utilise __str__
|
| f"{a}"
| __format__(self, formatstr)
| Insertion dans un formatage |
| hash(a)
| __hash__(self)
| Condensat |
| sys.getsizeof(a)
| __sizeof__(self)
| Taille mémoire |
Pour les conteneurs¶
Si la classe A
définit un conteneur d'objet de type b
et a
un conteneur.
On a i
un entier.
Op | Méthode | Descrption |
---|---|---|
len(a) |
__len__(self) |
Taille |
a[i] |
__getitem__(self, i) |
Retourne le (i+1)-ième élément |
a[i] = b |
__setitem__(self, i, b) |
Affectation du (i+1)-ième élement |
def a[i] |
__delitem__(self, i) |
Détruit le (i+1)-ième élément |
for b in a: |
__iter__(self) |
Itérateur sur les élements |
reverse(a) |
__reverse__(self) |
Inverse l'ordre des éléments |
b in a |
__contains__(self) |
Est-ce que a contient b ? |
Here is the list of magic methods in Python: https://docs.python.org/3/reference/datamodel.html
{{ PreviousNext("04 View vs Copy.ipynb", "11 Decorators.ipynb")}}