{"id":2593,"date":"2021-10-19T15:38:13","date_gmt":"2021-10-19T15:38:13","guid":{"rendered":"https:\/\/www.pythontutorial.net\/?page_id=2593"},"modified":"2025-03-31T09:00:50","modified_gmt":"2025-03-31T09:00:50","slug":"python-__hash__","status":"publish","type":"page","link":"https:\/\/www.pythontutorial.net\/python-oop\/python-__hash__\/","title":{"rendered":"Python __hash__"},"content":{"rendered":"\n<p><strong>Summary<\/strong>: in this tutorial, you&#8217;ll learn about the Python hash() function and how to override the <code>__hash__<\/code> method in a custom class.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id='introduction-to-the-python-hash-function'>Introduction to the Python hash function <a href=\"#introduction-to-the-python-hash-function\" class=\"anchor\" id=\"introduction-to-the-python-hash-function\" title=\"Anchor for Introduction to the Python hash function\">#<\/a><\/h2>\n\n\n\n<p>Let&#8217;s start with a simple example.<\/p>\n\n\n\n<p>First, define the <code>Person<\/code> <a href=\"https:\/\/www.pythontutorial.net\/python-oop\/python-class\/\">class<\/a> with the <code>name<\/code> and <code>age<\/code> attributes:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-1\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-class\"><span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">Person<\/span>:<\/span>\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">__init__<\/span><span class=\"hljs-params\">(self, name, age)<\/span>:<\/span>\n        self.name = name\n        self.age = age<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-1\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Second, create two instances of the <code>Person<\/code> class:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-2\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">p1 = Person(<span class=\"hljs-string\">'John'<\/span>, <span class=\"hljs-number\">22<\/span>)\np2 = Person(<span class=\"hljs-string\">'Jane'<\/span>, <span class=\"hljs-number\">22<\/span>)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-2\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Third, show the hashes of the <code>p1<\/code> and <code>p2<\/code> objects:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-3\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">print(hash(p1))\nprint(hash(p2))<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-3\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Output:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-4\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-number\">110373112736<\/span>\n<span class=\"hljs-number\">110373572343<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-4\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Here&#8217;s the complete script:<\/p>\n\n\n<pre class=\"wp-block-code\"><span><code class=\"hljs\">class Person:\n    def __init__(self, name, age):\n        self.name = name\n        self.age = age\n        \np1 = Person('John', 22)\np2 = Person('Jane', 22)        \n\nprint(hash(p1))\nprint(hash(p2))<\/code><\/span><\/pre>\n\n\n<p><a href=\"https:\/\/www.pythontutorial.net\/playground\/?q=Y2xhc3MgUGVyc29uOgogICAgZGVmIF9faW5pdF9fKHNlbGYsIG5hbWUsIGFnZSk6CiAgICAgICAgc2VsZi5uYW1lID0gbmFtZQogICAgICAgIHNlbGYuYWdlID0gYWdlCiAgICAgICAgCnAxID0gUGVyc29uKCdKb2huJywgMjIpCnAyID0gUGVyc29uKCdKYW5lJywgMjIpICAgICAgICAKCnByaW50KGhhc2gocDEpKQpwcmludChoYXNoKHAyKSk%3D\" target=\"_blank\" rel=\"noreferrer noopener\">Try it<\/a><\/p>\n\n\n\n<p>The <code>hash()<\/code> function accepts an object and returns the hash value as an integer. When you pass an object to the <code>hash()<\/code> function, Python will execute the <code>__hash__<\/code> special method of the object.<\/p>\n\n\n\n<p>It means that when you pass the <code>p1<\/code> object to the <code>hash()<\/code> function:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-5\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">hash(p1)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-5\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Python will call the <code>__hash__<\/code> method of the <code>p1<\/code> object:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-6\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">p1.__hash__()<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-6\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>By default, the <code>__hash__<\/code> uses the object&#8217;s identity and the <code><a href=\"https:\/\/www.pythontutorial.net\/python-oop\/python-__eq__\/\">__eq__<\/a><\/code> returns <code>True<\/code> if two objects are the same. To override this default behavior, you can implement the <code>__eq__<\/code> and <code>__hash__<\/code>.<\/p>\n\n\n\n<p>If a class overrides the <code>__eq__<\/code> method, the objects of the class become unhashable. This means that you won&#8217;t able to use the objects in a mapping type. For example, you will not able to use them as keys in a <a href=\"https:\/\/www.pythontutorial.net\/python-basics\/python-dictionary\/\">dictionary<\/a> or elements in a <a href=\"https:\/\/www.pythontutorial.net\/python-basics\/python-set\/\">set<\/a>.<\/p>\n\n\n\n<p>The following <code>Person<\/code> class implements the <code>__eq__<\/code> method:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-7\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-class\"><span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">Person<\/span>:<\/span>\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">__init__<\/span><span class=\"hljs-params\">(self, name, age)<\/span>:<\/span>\n        self.name = name\n        self.age = age\n\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">__eq__<\/span><span class=\"hljs-params\">(self, other)<\/span>:<\/span>\n        <span class=\"hljs-keyword\">return<\/span> isinstance(other, Person) <span class=\"hljs-keyword\">and<\/span> self.age == other.age<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-7\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>If you attempt to use the <code>Person<\/code> object in a set, you&#8217;ll get an error. For example:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-8\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">members = {\n    Person(<span class=\"hljs-string\">'John'<\/span>, <span class=\"hljs-number\">22<\/span>),\n    Person(<span class=\"hljs-string\">'Jane'<\/span>, <span class=\"hljs-number\">22<\/span>)\n}<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-8\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Python issues the following error:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-9\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">TypeError: unhashable type: <span class=\"hljs-string\">'Person'<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-9\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Also, the Person&#8217;s object loses hashing because if you implement <code>__eq__<\/code>, the <code>__hash__<\/code> is set to <code>None<\/code>. For example:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-10\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">hash(Person(<span class=\"hljs-string\">'John'<\/span>, <span class=\"hljs-number\">22<\/span>))<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-10\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Error:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-11\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">TypeError: unhashable type: <span class=\"hljs-string\">'Person'<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-11\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>To make the <code>Person<\/code> class hashable, you also need to implement the <code>__hash__<\/code> method:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-12\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-class\"><span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">Person<\/span>:<\/span>\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">__init__<\/span><span class=\"hljs-params\">(self, name, age)<\/span>:<\/span>\n        self.name = name\n        self.age = age\n\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">__eq__<\/span><span class=\"hljs-params\">(self, other)<\/span>:<\/span>\n        <span class=\"hljs-keyword\">return<\/span> isinstance(other, Person) <span class=\"hljs-keyword\">and<\/span> self.age == other.age\n\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">__hash__<\/span><span class=\"hljs-params\">(self)<\/span>:<\/span>\n        <span class=\"hljs-keyword\">return<\/span> hash(self.age)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-12\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Now, you have the <code>Person<\/code> class that supports equality based on <code>age<\/code> and is hashable.<\/p>\n\n\n\n<p>To make the <code>Person<\/code> work well in data structures like dictionaries, the hash of the class should remain immutable. To do it, you can make the <code>age<\/code> attribute of the <code>Person<\/code> class a <a href=\"https:\/\/www.pythontutorial.net\/python-oop\/python-readonly-property\/\">read-only property<\/a>:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-13\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-class\"><span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">Person<\/span>:<\/span>\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">__init__<\/span><span class=\"hljs-params\">(self, name, age)<\/span>:<\/span>\n        self.name = name\n        self._age = age\n\n<span class=\"hljs-meta\">    @property<\/span>\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">age<\/span><span class=\"hljs-params\">(self)<\/span>:<\/span>\n        <span class=\"hljs-keyword\">return<\/span> self._age\n\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">__eq__<\/span><span class=\"hljs-params\">(self, other)<\/span>:<\/span>\n        <span class=\"hljs-keyword\">return<\/span> isinstance(other, Person) <span class=\"hljs-keyword\">and<\/span> self.age == other.age\n\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">__hash__<\/span><span class=\"hljs-params\">(self)<\/span>:<\/span>\n        <span class=\"hljs-keyword\">return<\/span> hash(self.age)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-13\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h2 class=\"wp-block-heading\" id='summary'>Summary <a href=\"#summary\" class=\"anchor\" id=\"summary\" title=\"Anchor for Summary\">#<\/a><\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>By default, <code>__hash__<\/code> uses the id of objects and <code>__eq__<\/code> uses the <code>is<\/code> operator for comparisons.<\/li>\n\n\n\n<li>If you implement <code>__eq__<\/code>, Python sets <code>__hash__<\/code> to <code>None<\/code> unless you implement <code>__hash__<\/code>.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\" id='quiz'>Quiz <a href=\"#quiz\" class=\"anchor\" id=\"quiz\" title=\"Anchor for Quiz\">#<\/a><\/h2>\n\n\n\n<iframe loading=\"lazy\"\n  name=\"quiz\"\n  src=\"\/quiz\/?quiz=__eq__\"\n  height=\"700\"\n  width=\"600\"\n  class=\"iframe\"\n><\/iframe>\n\n<div class=\"helpful-block-content\" data-title=\"\">\n\t<header>\n\t\t<div class=\"wth-question\">Was this tutorial helpful ?<\/div>\n\t\t<div class=\"wth-thumbs\">\n\t\t\t<button\n\t\t\t\tdata-post=\"2593\"\n\t\t\t\tdata-post-url=\"https:\/\/www.pythontutorial.net\/python-oop\/python-__hash__\/\"\n\t\t\t\tdata-post-title=\"Python __hash__\"\n\t\t\t\tdata-response=\"1\"\n\t\t\t\tclass=\"wth-btn-rounded wth-yes-btn\"\n\t\t\t>\n\t\t\t\t<svg\n\t\t\t\t\txmlns=\"http:\/\/www.w3.org\/2000\/svg\"\n\t\t\t\t\tviewBox=\"0 0 24 24\"\n\t\t\t\t\tfill=\"none\"\n\t\t\t\t\tstroke=\"currentColor\"\n\t\t\t\t\tstroke-width=\"2\"\n\t\t\t\t\tstroke-linecap=\"round\"\n\t\t\t\t\tstroke-linejoin=\"round\"\n\t\t\t\t\tclass=\"feather feather-thumbs-up block w-full h-full\"\n\t\t\t\t>\n\t\t\t\t\t<path\n\t\t\t\t\t\td=\"M14 9V5a3 3 0 0 0-3-3l-4 9v11h11.28a2 2 0 0 0 2-1.7l1.38-9a2 2 0 0 0-2-2.3zM7 22H4a2 2 0 0 1-2-2v-7a2 2 0 0 1 2-2h3\"\n\t\t\t\t\t><\/path>\n\t\t\t\t<\/svg>\n\t\t\t\t<span class=\"sr-only\"> Yes <\/span>\n\t\t\t<\/button>\n\n\t\t\t<button\n\t\t\t\tdata-response=\"0\"\n\t\t\t\tdata-post=\"2593\"\n\t\t\t\tdata-post-url=\"https:\/\/www.pythontutorial.net\/python-oop\/python-__hash__\/\"\n\t\t\t\tdata-post-title=\"Python __hash__\"\n\t\t\t\tclass=\"wth-btn-rounded wth-no-btn\"\n\t\t\t>\n\t\t\t\t<svg\n\t\t\t\t\txmlns=\"http:\/\/www.w3.org\/2000\/svg\"\n\t\t\t\t\tviewBox=\"0 0 24 24\"\n\t\t\t\t\tfill=\"none\"\n\t\t\t\t\tstroke=\"currentColor\"\n\t\t\t\t\tstroke-width=\"2\"\n\t\t\t\t\tstroke-linecap=\"round\"\n\t\t\t\t\tstroke-linejoin=\"round\"\n\t\t\t\t>\n\t\t\t\t\t<path\n\t\t\t\t\t\td=\"M10 15v4a3 3 0 0 0 3 3l4-9V2H5.72a2 2 0 0 0-2 1.7l-1.38 9a2 2 0 0 0 2 2.3zm7-13h2.67A2.31 2.31 0 0 1 22 4v7a2.31 2.31 0 0 1-2.33 2H17\"\n\t\t\t\t\t><\/path>\n\t\t\t\t<\/svg>\n\t\t\t\t<span class=\"sr-only\"> No <\/span>\n\t\t\t<\/button>\n\t\t<\/div>\n\t<\/header>\n\n\t<div class=\"wth-form hidden\">\n\t\t<div class=\"wth-form-wrapper\">\n\t\t\t<div class=\"wth-title\"><\/div>\n\t\t\t<textarea class=\"wth-message\"><\/textarea>\n\t\t\t<input type=\"button\" name=\"wth-submit\" class=\"wth-btn wth-btn-submit\" id=\"wth-submit\" \/>\n\t\t\t<input type=\"button\" class=\"wth-btn wth-btn-cancel\" value=\"Cancel\" \/>\n\t\t<\/div>\n\t<\/div>\n<\/div>\n","protected":false},"excerpt":{"rendered":"<p>In this tutorial, you&#8217;ll learn about the Python hash() function and how to override the __hash__ method in a custom class.<\/p>\n","protected":false},"author":1,"featured_media":0,"parent":417,"menu_order":13,"comment_status":"closed","ping_status":"closed","template":"","meta":{"footnotes":""},"class_list":["post-2593","page","type-page","status-publish","hentry"],"_links":{"self":[{"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/pages\/2593","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/comments?post=2593"}],"version-history":[{"count":2,"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/pages\/2593\/revisions"}],"predecessor-version":[{"id":7302,"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/pages\/2593\/revisions\/7302"}],"up":[{"embeddable":true,"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/pages\/417"}],"wp:attachment":[{"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/media?parent=2593"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}