Metoda Python hash().

Funcția Python hash(). este o funcție încorporată și returnează valoarea hash a unui obiect dacă are una. Valoarea hash este un număr întreg care este folosit pentru a compara rapid cheile de dicționar în timp ce se uită la a dicţionar .

Sintaxa funcției Python hash().

Sintaxa: hash(obj)

Parametri : obj : Obiectul pe care trebuie să-l transformăm în hash.

Se intoarce : Returnează valoarea hashing dacă este posibil.

Proprietățile funcției hash().

  • Obiectele analizate folosind hash() sunt ireversibile, ceea ce duce la pierderea de informații.
  • hash() returnează valoarea hash numai pentru obiectele imuabile, prin urmare poate fi folosit ca indicator pentru a verifica dacă există obiecte mutabile/imuabile.
  • Putem codifica datele pentru securitate în Python utilizând funcția hash().

Exemple de funcții Python hash().

Exemplul 1: Demonstrarea funcționării hash()

În acest exemplu, folosim funcția hash() pentru a imprima valoarea hash întreg, șir și float folosind hash() în Piton .

Python3




# 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)))>

Ieșire

The integer hash value is : 4 The string hash value is : 4349415460800802357 The float hash value is : 1291272085159665688 

Exemplul 2: Demonstrarea proprietății hash()

Acest cod Python demonstrează modul în care hash()> funcția se comportă cu obiecte imuabile și mutabile . Mai întâi inițializează un tuplu și o listă cu aceleași elemente. Codul imprimă cu succes valoarea hash a tuplului. Cu toate acestea, atunci când încearcă să imprime valoarea hash a listei, care este mutabilă, ridică a TypeError> deoarece obiectele mutabile, cum ar fi listele, nu pot fi indexate direct.

Python3




# 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)))>

Ieșire:

The tuple hash value is : 8315274433719620810 

Excepții:

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' 

Exemplul 3: hash() pentru obiect tuplu imuabil

Acest cod Python inițializează un tuplu numit var> care conțin caracterele „G”, „E”, „E” și „K”. The hash()> funcția este utilizată pentru a genera o valoare hash pentru tuplu var> . În acest caz, codul imprimă valoarea hash a tuplului, care este un număr întreg unic care reprezintă tuplul pe baza conținutului și structurii sale.

Python3




# hash() for immutable tuple object> var> => (> 'G'> ,> 'E'> ,> 'E'> ,> 'K'> )> print> (> hash> (var))>

Ieșire

3843673861956289951 

Exemplul 4: hash() activat lor Obiect utilizabil

Metoda hash() folosită de un obiect imuabil, dacă o folosim pe un obiect mutabil precum listă, set, dicționare, atunci va genera o eroare.

Python3




l> => [> 1> ,> 2> ,> 3> ,> 4> ]> print> (> hash> (l))>

Ieșire

TypeError: unhashable type: 'list' 

Exemplul 5: hash() pe un obiect personalizat

Aici vom suprascrie metodele __hash()__ pentru a apela hash(), iar metoda __eq__() va verifica egalitatea celor două obiecte personalizate.

Python3




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))>

Ieșire

The hash is: 7627717261227283506 The hash is: 7627717261227283506