English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Tutoriel de base Python

Contrôle de flux Python

Fonctions en Python

Types de données en Python

Opérations de fichiers Python

Objets et classes Python

Dates et heures Python

Connaissances avancées Python

Manuel de référence Python

Utilisation et exemples de hash() en Python

Python built-in functions

La méthode hash() renvoie la valeur de hachage d'un objet (s'il y en a une).

La valeur de hachage est simplement un certain nombre d'entiers, utilisé pendant la recherche dans le dictionnaire pour comparer les clés du dictionnaire.

En interne, la méthode hash() appelle la méthode __hash__() de l'objet, qui est définie par défaut pour tout objet. Nous y reviendrons plus tard.

La syntaxe de la méthode hash() est :

hash(object)

paramètre hash()

La méthode hash() prend un paramètre :

  • objet -l'objet à renvoyer sa valeur de hachage (entier, chaîne, nombre flottant)

valeur de hachage renvoyée

La méthode hash() renvoie la valeur de hachage d'un objet (s'il y en a une).

Si l'objet a une méthode __hash__() personnalisée, il renverra une valeur tronquée àPy_ssize_ttaille.

Example1:Comment la méthode hash() fonctionne-t-elle en Python ?

# La valeur de hachage d'un entier reste inchangée
print('181le hachage est :181))

print('181.23le hachage est :181.23))
# Hachage de chaîne
print('Le hachage de Python est :', hash('Python'))

The output when running the program is:

181le hachage est : 181
181.23le hachage est : 579773580
Le hachage de Python est : 2101984854

Example2?hash() d'un objet tuple immuable ?

La méthode hash() ne s'applique qu'aux objets immuables, tels quetuple.

# Ensemble des voyelles
vowels = ('a', 'e', 'i', 'o', 'u')
print('hash est :', hash(vowels))

The output when running the program is:

hash is: -695778075465126279

Comment utiliser hash() pour les objets personnalisés ?

Comme mentionné précédemment, la méthode hash() appelle la méthode __hash__() en interne. Par conséquent, tout objet peut surcharger __hash__() pour obtenir une valeur de hachage personnalisée.

But for a correct hash implementation, __hash__ () should always return an integer. And, both __eq__ () and __hash__ () methods must be implemented simultaneously.

Below is the correct rewriting of __hash__ ()

Cases of custom hash implementation of objects
__eq__ ()__hash__ ()Description

Defined (by default)

Defined (by default)

If left as is, all object comparisons are unequal (except for themselves)

(if mutable) Defined

Should not be defined

To implement hashable collections, the hash values of the keys must be immutable

Not definedShould not be definedIf __eq__ () is not defined, __hash__ () should not be defined.
DefinedNot defined

The class example cannot be used as a hashable collection.

__hash__ () is implicitly set toNone

A TypeError exception is raised if the hash is attempted to be retrieved.

DefinedKeep from parent class__hash__ = <ParentClass>.__hash__
DefinedNot hashed

__hash__ = None

A TypeError exception is raised if the hash is attempted to be retrieved.

Example3: Custom object hash() by rewriting __hash__ ()

class Person:
    def __init__(self, age, name):
        self.age = age
        self.name = name
    def __eq__(self, other):
        return self.age == other.age and self.name == other.name
    def __hash__(self):
        print('hash is:')
        return hash((self.age, self.name))
person = Person(23, 'Adam')
print(hash(person))

The output when running the program is:

hash is:
3785419240612877014

Note:You do not need to implement the __eq__ () method for hash, because it will be created by default for all objects.

Python built-in functions