English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Il metodo hash() restituisce il valore di hash di un oggetto (se presente).
Il valore di hash è solo alcuni numeri interi utilizzati durante la ricerca della tabella di hash per confrontare le chiavi del dizionario.
Internalmente, il metodo hash() chiama il metodo __hash__() dell'oggetto, che di default è impostato per qualsiasi oggetto. Vedremo questo più tardi.
La sintassi del metodo hash() è:
hash(object)
Parametro hash()
oggetto - Oggetto da restituire il valore di hash (intero, stringa, numero decimale)
Il metodo hash() restituisce il valore di hash di un oggetto (se presente).
Se l'oggetto ha un metodo __hash__() personalizzato, restituirà un valore troncato aPy_ssize_tdella dimensione.
# Il valore di hash degli interi rimane invariato print('L'hash di 181 è:', hash(181)) # Hash decimale print('L'hash di 181.23 è:', hash(181.23)) # Hash della stringa print('L'hash di Python è:', hash('Python'))
运行该程序时,输出为:
L'hash di 181 è: 181 L'hash di 181.23 è: 579773580 L'hash di Python è: 2101984854
Il metodo hash() si applica solo agli oggetti immutabili, cometuple.
# Tuple di vocali vowels = ('a', 'e', 'i', 'o', 'u') print('hash è:', hash(vowels))
运行该程序时,输出为:
hash è: -695778075465126279
Come descritto sopra, il metodo hash() chiama internamente il metodo __hash__(). Pertanto, qualsiasi oggetto può sovrascrivere __hash__() per ottenere un valore di hash personalizzato.
Ma per un'implementazione corretta dell'hash, __hash__() dovrebbe sempre restituire un intero. E deve essere implementato sia __eq__() che __hash__().
下面是正确的__hash__()重写的情况。
__eq__() | __hash__() | 描述 |
---|---|---|
已定义(默认情况下) | 已定义(默认情况下) | 如果保持原样,所有对象的比较都是不相等的(除了它们自己) |
(如果可变)已定义 | 不应该定义 | 实现hashable集合需要键的散列值是不可变的 |
没有定义 | 不应该定义 | 如果未定义__eq__(),则不应定义__hash__()。 |
已定义 | 没有定义 | 类示例将不能用作可哈希收集。 __hash__()隐式设置为None 如果尝试检索哈希,则引发TypeError异常。 |
已定义 | 保留从父类 | __hash__ = <ParentClass> .__ hash__ |
已定义 | 不散列 | __hash__ =None 如果尝试检索哈希,则引发TypeError异常。 |
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是:') return hash((self.age, self.name)) person = Person(23, 'Adam') print(hash(person))
运行该程序时,输出为:
hash是: 3785419240612877014
注意:您不必为哈希实现__eq__()方法,因为默认情况下会为所有对象创建哈希。