Mètode Python hash().
Funció hash() de Python és una funció integrada i retorna el valor hash d'un objecte si en té un. El valor hash és un nombre enter que s'utilitza per comparar ràpidament les claus del diccionari mentre es mira a diccionari .
Sintaxi de la funció hash() de Python
Sintaxi: hash (obj)
Paràmetres: obj: L'objecte que hem de convertir en hash.
Devolucions: Retorna el valor hash si és possible.
Propietats de la funció hash().
- Els objectes hash utilitzant hash() són irreversibles, provocant la pèrdua d'informació.
- hash() retorna el valor hash només per als objectes immutables, per tant es pot utilitzar com a indicador per comprovar si hi ha objectes mutables/immutables.
- Podem codificar dades per seguretat a Python mitjançant la funció hash().
Exemples de funcions Python hash().
Exemple 1: Demostració del funcionament de hash()
En aquest exemple, estem utilitzant la funció hash() per imprimir el valor hash d'enter, cadena i float utilitzant hash() a Python .
Python 3
# initializing objects> int_val> => 4> str_val> => 'techcodeview.com'> flt_val> => 24.56> # Printing the hash values.> # Notice Integer value doesn't change> # You'll have answer later in article.> print> (> 'The integer hash value is : '> +> str> (> hash> (int_val)))> print> (> 'The string hash value is : '> +> str> (> hash> (str_val)))> print> (> 'The float hash value is : '> +> str> (> hash> (flt_val)))> |
Sortida
The integer hash value is : 4 The string hash value is : 4349415460800802357 The float hash value is : 1291272085159665688
Exemple 2: Demostració de la propietat de hash()
Aquest codi de Python demostra com hash()> funció es comporta amb objectes immutables i mutables . Primer inicialitza una tupla i una llista amb els mateixos elements. El codi imprimeix correctament el valor hash de la tupla. Tanmateix, quan intenta imprimir el valor hash de la llista, que és mutable, genera a TypeError> perquè els objectes mutables com les llistes no es poden utilitzar directament.
Python 3
# initializing objects> # tuple are immutable> tuple_val> => (> 1> ,> 2> ,> 3> ,> 4> ,> 5> )> # list are mutable> list_val> => [> 1> ,> 2> ,> 3> ,> 4> ,> 5> ]> # Printing the hash values.> # Notice exception when trying> # to convert mutable object> print> (> 'The tuple hash value is : '> +> str> (> hash> (tuple_val)))> print> (> 'The list hash value is : '> +> str> (> hash> (list_val)))> |
Sortida:
The tuple hash value is : 8315274433719620810
Excepcions:
Traceback (most recent call last): File '/home/eb7e39084e3d151114ce5ed3e43babb8.py', line 15, in print ('The list hash value is : ' + str(hash(list_val))) TypeError: unhashable type: 'list' Exemple 3: hash() per a l'objecte de tupla immutable
Aquest codi de Python inicialitza una tupla anomenada var> que conté els caràcters 'G', 'E', 'E' i 'K'. El hash()> La funció s'utilitza per generar un valor hash per a la tupla var> . En aquest cas, el codi imprimeix el valor hash de la tupla, que és un nombre enter únic que representa la tupla en funció del seu contingut i estructura.
Python 3
# hash() for immutable tuple object> var> => (> 'G'> ,> 'E'> ,> 'E'> ,> 'K'> )> print> (> hash> (var))> |
Sortida
3843673861956289951
Exemple 4: hash() activat la M Objecte utilitzable
El mètode hash() utilitzat per un objecte immutable, si l'utilitzem en un objecte mutable com llista, conjunt, diccionaris, generarà un error.
Python 3
l> => [> 1> ,> 2> ,> 3> ,> 4> ]> print> (> hash> (l))> |
Sortida
TypeError: unhashable type: 'list'
Exemple 5: hash() en un objecte personalitzat
Aquí anularem els mètodes __hash()__ per cridar el hash(), i el mètode __eq__() comprovarà la igualtat dels dos objectes personalitzats.
Python 3
class> Emp:> > def> __init__(> self> , emp_name,> id> ):> > self> .emp_name> => emp_name> > self> .> id> => id> > def> __eq__(> self> , other):> > > # Equality Comparison between two objects> > return> self> .emp_name> => => other.emp_name> and> self> .> id> => => other.> id> > def> __hash__(> self> ):> > > # hash(custom_object)> > return> hash> ((> self> .emp_name,> self> .> id> ))> emp> => Emp(> 'Ragav'> ,> 12> )> print> (> 'The hash is: %d'> %> hash> (emp))> # We'll check if two objects with the same> # attribute values have the same hash> emp_copy> => Emp(> 'Ragav'> ,> 12> )> print> (> 'The hash is: %d'> %> hash> (emp_copy))> |
Sortida
The hash is: 7627717261227283506 The hash is: 7627717261227283506