{"id":158,"date":"2024-01-25T13:58:06","date_gmt":"2024-01-25T13:58:06","guid":{"rendered":"https:\/\/learnpython.elegantwallp.com\/?p=158"},"modified":"2024-01-25T13:58:11","modified_gmt":"2024-01-25T13:58:11","slug":"python-__hash__","status":"publish","type":"post","link":"https:\/\/learnpython.elegantwallp.com\/2024\/01\/25\/python-__hash__\/","title":{"rendered":"Python __hash__"},"content":{"rendered":"\n<p><strong>Summary<\/strong>: in this tutorial, you\u2019ll learn about the Python hash() function and how to override the&nbsp;<code>__hash__<\/code>&nbsp;method in a custom class.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Introduction to the Python hash function<\/h2>\n\n\n\n<p>Let\u2019s start with a simple example.<\/p>\n\n\n\n<p>First, define the\u00a0<code>Person<\/code>\u00a0class\u00a0with the\u00a0<code>name<\/code>\u00a0and\u00a0<code>age<\/code>\u00a0attributes:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>class Person: def __init__(self, name, age): self.name = name self.age = age<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>Second, create two instances of the\u00a0<code>Person<\/code>\u00a0class:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>p1 = Person('John', 22) p2 = Person('Jane', 22)<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>Third, show the hashes of the\u00a0<code>p1<\/code>\u00a0and\u00a0<code>p2<\/code>\u00a0objects:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>print(hash(p1)) print(hash(p2))<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>Output:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>110373112736 110373572343<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>The&nbsp;<code>hash()<\/code>&nbsp;function accepts an object and returns the hash value as an integer. When you pass an object to the&nbsp;<code>hash()<\/code>&nbsp;function, Python will execute the&nbsp;<code>__hash__<\/code>&nbsp;special method of the object.<\/p>\n\n\n\n<p>It means that when you pass the\u00a0<code>p1<\/code>\u00a0object to the\u00a0<code>hash()<\/code>\u00a0function:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>hash(p1)<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>Python will call the\u00a0<code>__hash__<\/code>\u00a0method of the\u00a0<code>p1<\/code>\u00a0object:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>p1.__hash__()<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>By default, the&nbsp;<code>__hash__<\/code>&nbsp;uses the object\u2019s identity and the&nbsp;<code><a href=\"https:\/\/www.pythontutorial.net\/python-oop\/python-__eq__\/\">__eq__<\/a><\/code>&nbsp;returns&nbsp;<code>True<\/code>&nbsp;if two objects are the same. To override this default behavior, you can implement the&nbsp;<code>__eq__<\/code>&nbsp;and&nbsp;<code>__hash__<\/code>.<\/p>\n\n\n\n<p>If a class overrides the\u00a0<code>__eq__<\/code>\u00a0method, the objects of the class become unhashable. This means that you won\u2019t able to use the objects in a mapping type. For example, you will not able to use them as keys in a\u00a0dictionary\u00a0or elements in a\u00a0set.<\/p>\n\n\n\n<p>The following\u00a0<code>Person<\/code>\u00a0class implements the\u00a0<code>__eq__<\/code>\u00a0method:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>class Person: def __init__(self, name, age): self.name = name self.age = age def __eq__(self, other): return isinstance(other, Person) and self.age == other.age<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>If you attempt to use the\u00a0<code>Person<\/code>\u00a0object in a set, you\u2019ll get an error. For example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>members = { Person('John', 22), Person('Jane', 22) }<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>Python issues the following error:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>TypeError: unhashable type: 'Person'<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>Also, the Person\u2019s object loses hashing because if you implement\u00a0<code>__eq__<\/code>, the\u00a0<code>__hash__<\/code>\u00a0is set to\u00a0<code>None<\/code>. For example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>hash(Person('John', 22))<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>Error:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>TypeError: unhashable type: 'Person'<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>To make the\u00a0<code>Person<\/code>\u00a0class hashable, you also need to implement the\u00a0<code>__hash__<\/code>\u00a0method:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>class Person: def __init__(self, name, age): self.name = name self.age = age def __eq__(self, other): return isinstance(other, Person) and self.age == other.age def __hash__(self): return hash(self.age)<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>Now, you have the&nbsp;<code>Person<\/code>&nbsp;class that supports equality based on&nbsp;<code>age<\/code>&nbsp;and is hashable.<\/p>\n\n\n\n<p>To make the\u00a0<code>Person<\/code>\u00a0work well in data structures like dictionaries, the hash of the class should remain immutable. To do it, you can make the\u00a0<code>age<\/code>\u00a0attribute of the\u00a0<code>Person<\/code>\u00a0class a\u00a0read-only property:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>class Person: def __init__(self, name, age): self.name = name self._age = age @property def age(self): return self._age def __eq__(self, other): return isinstance(other, Person) and self.age == other.age def __hash__(self): return hash(self.age)<\/code><\/code><\/pre>\n","protected":false},"excerpt":{"rendered":"<p>Summary: in this tutorial, you\u2019ll learn about the Python hash() function and how to override the&nbsp;__hash__&nbsp;method in a custom class. Introduction to the Python hash function Let\u2019s start with a simple example. First, define the\u00a0Person\u00a0class\u00a0with the\u00a0name\u00a0and\u00a0age\u00a0attributes: Second, create two instances of the\u00a0Person\u00a0class: Third, show the hashes of the\u00a0p1\u00a0and\u00a0p2\u00a0objects: Output: The&nbsp;hash()&nbsp;function accepts an object and returns [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[26],"tags":[],"class_list":["post-158","post","type-post","status-publish","format-standard","hentry","category-2-special-methods"],"_links":{"self":[{"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/posts\/158","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/comments?post=158"}],"version-history":[{"count":1,"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/posts\/158\/revisions"}],"predecessor-version":[{"id":159,"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/posts\/158\/revisions\/159"}],"wp:attachment":[{"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/media?parent=158"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/categories?post=158"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/tags?post=158"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}