{"id":81,"date":"2014-12-02T17:00:24","date_gmt":"2014-12-02T22:00:24","guid":{"rendered":"http:\/\/pfsensesetup.com\/pythonscript.net\/?p=81"},"modified":"2014-12-02T11:19:37","modified_gmt":"2014-12-02T16:19:37","slug":"classes-and-inheritance-part-two","status":"publish","type":"post","link":"http:\/\/pfsensesetup.com\/pythonscript.net\/classes-and-inheritance-part-two\/","title":{"rendered":"Classes and Inheritance: Part Two"},"content":{"rendered":"<p><a href=\"http:\/\/pfsensesetup.com\/pythonscript.net\/wp-content\/uploads\/2014\/10\/python_logo_3d_by_technopathic-d4qgd9q.png\"><img loading=\"lazy\" decoding=\"async\" class=\"alignleft size-medium wp-image-32\" src=\"http:\/\/pfsensesetup.com\/pythonscript.net\/wp-content\/uploads\/2014\/10\/python_logo_3d_by_technopathic-d4qgd9q-300x225.png\" alt=\"classes\" width=\"300\" height=\"225\" srcset=\"http:\/\/pfsensesetup.com\/pythonscript.net\/wp-content\/uploads\/2014\/10\/python_logo_3d_by_technopathic-d4qgd9q-300x225.png 300w, http:\/\/pfsensesetup.com\/pythonscript.net\/wp-content\/uploads\/2014\/10\/python_logo_3d_by_technopathic-d4qgd9q.png 800w\" sizes=\"auto, (max-width: 300px) 100vw, 300px\" \/><\/a>In <a href=\"http:\/\/pfsensesetup.com\/pythonscript.net\/classes-inheritance-part-one\/\">the previous article<\/a>, we introduced Python classes, discussed some of their features, and some of the similarities and differences from C++ classes. In this article, we will use our knowledge of C++ classes to rewrite our hash functions as a Python class.<\/p>\n<h3><span style=\"text-decoration: underline;\"><strong>Writing the HashObject Class<\/strong><\/span><\/h3>\n<p>Our first job is to write the class constructor. Since it makes sense to initialize our list when the class is first instantiated, I decided to incorporate the createBuckets() function as part of the constructor:<\/p>\n<pre><span style=\"color: #0000ff;\"><strong>class HashObject(object):\r\n    def __init__(self, num):\r\n        self.numBuckets = num\r\n        self.hashSet = []\r\n        for i in range(num):\r\n            self.hashSet.append([])\r\n<\/strong><\/span><\/pre>\n<p>This constructor takes one parameter (num), and assigns it to numBuckets, and then initializes our list.<\/p>\n<p>Next, we want to define hashElement, which takes a number and hashes it to an index in hashSet. This function is the same as before, except that we do not have to pass the number of buckets to it:<\/p>\n<pre><span style=\"color: #0000ff;\"><strong>def hashElement(self, elem):\r\n        if type(elem) == int:\r\n            return elem%self.numBuckets\r\n<\/strong><\/span><\/pre>\n<p>The new insert function requires only one parameter: the list item to be inserted into one of the buckets:<\/p>\n<pre><span style=\"color: #0000ff;\"><strong>def insert(self, i):\r\n        self.hashSet[self.hashElement(i[0])].append(i)\r\n<\/strong><\/span><\/pre>\n<p>Note that it is assumed that the first element of the list to be stored is assumed to be the key. Next, we need a remove function. We will take one parameter: the key value of the item to be deleted:<\/p>\n<pre><span style=\"color: #0000ff;\"><strong>def remove(self, key):\r\n        newElement = []\r\n        for j in self.hashSet[self.hashElement(key)]:\r\n            if j[0] != key:\r\n                newElement.append(j)\r\n        self.hashSet[self.hashElement(key)] = newElement  <\/strong>  \r\n<\/span><\/pre>\n<p>Finally, we need to write the function to check to see if an item with a certain key exists:<\/p>\n<pre><span style=\"color: #0000ff;\"><strong>def member(self, key):\r\n        return i in self.hashSet[hashElement(key)]\r\n<\/strong><\/span><\/pre>\n<p>One additional member function we may want to define is an accessor function for hashSet so we do not have to directly access the list, a good practice, since data hiding is one of the objectives of object-oriented programming:<\/p>\n<pre><span style=\"color: #0000ff;\"><strong>def getElement(self, key):\r\n        for j in self.hashSet[self.hashElement(key)]:\r\n            if j[0] == key:\r\n                return j\r\n<\/strong><\/span><\/pre>\n<p>As you can see, we iterate through each list item in the bucket the key value hashes to (multiple items may be stored in a single bucket). When we find an item whose first value equals the key, we return that item.<\/p>\n<p>With variables and member functions for HashObject defined, we can rewrite hashTest to test our class:<\/p>\n<pre><span style=\"color: #0000ff;\"><strong>def hashTest():\r\n    h = HashObject(51)\r\n    h.insert([2175,'Homer Simpson','Technician',20])\r\n    print(h.getElement(2175))\r\n    h.insert([4158,'Elmer Higgins','Engineer',17])\r\n    print(h.getElement(4158))\r\n    h.insert([2583,'Waylon Smithers','Assistant',25])\r\n    print(h.getElement(2583))\r\n    h.remove(2175)\r\n    print(h.getElement(2175))\r\n    print(h.getElement(2583))\r\n<\/strong><\/span><\/pre>\n<p>Running this function results in the following output:<\/p>\n<p><strong>[2175, &#8216;Homer Simpson&#8217;, &#8216;Technician&#8217;, 20]<\/strong><br \/>\n<strong> [4158, &#8216;Elmer Higgins&#8217;, &#8216;Engineer&#8217;, 17]<\/strong><br \/>\n<strong> [2583, &#8216;Waylon Smithers&#8217;, &#8216;Assistant&#8217;, 25]<\/strong><br \/>\n<strong> None<\/strong><br \/>\n<strong> [2583, &#8216;Waylon Smithers&#8217;, &#8216;Assistant&#8217;, 25]<\/strong><\/p>\n<p>In this function, we first create a hash set with 51 buckets. We insert the first record (Homer Simpson&#8217;s), and print it out, confirming its successful insertion. We insert a second record, also printing it out to confirm its insertion. Then we enter a third item (which, incidentally, hashes to the same location as the first item), and print it out, confirming its insertion and also confirming that we can successfully iterate through a bucket. Finally, we remove the first record and try to print it out. Since the getElement function will not return a value for a nonexistent record, the print call prints out &#8220;None&#8221;, for no value. Finally, we successfully print out the third record.<\/p>\n<p>I have made HashObject and HashTest available for download <a href=\"http:\/\/pythonscript.net\/pythonscripts\/hashing.py\">here<\/a>, so you can download it, run it and modify it to your heart&#8217;s content.<\/p>\n<h3><span style=\"text-decoration: underline;\"><strong>External Links:<\/strong><\/span><\/h3>\n<p><a href=\"https:\/\/docs.python.org\/3\/tutorial\/classes.html\">Classes Tutorial on python.org<\/a><\/p>\n<p><a href=\"http:\/\/en.wikipedia.org\/wiki\/Class_(computer_programming)\">Class (computer programming) on Wikipedia<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>In the previous article, we introduced Python classes, discussed some of their features, and some of the similarities and differences from C++ classes. In this article, we will use our knowledge of C++ classes to rewrite our hash functions as a Python class. Writing the HashObject Class Our first job is to write the class [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[7,3],"tags":[44,50,49,45],"class_list":["post-81","post","type-post","status-publish","format-standard","hentry","category-guides","category-tutorials","tag-classes","tag-constructor","tag-hashing","tag-inheritance","entry"],"_links":{"self":[{"href":"http:\/\/pfsensesetup.com\/pythonscript.net\/wp-json\/wp\/v2\/posts\/81","targetHints":{"allow":["GET"]}}],"collection":[{"href":"http:\/\/pfsensesetup.com\/pythonscript.net\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"http:\/\/pfsensesetup.com\/pythonscript.net\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"http:\/\/pfsensesetup.com\/pythonscript.net\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"http:\/\/pfsensesetup.com\/pythonscript.net\/wp-json\/wp\/v2\/comments?post=81"}],"version-history":[{"count":1,"href":"http:\/\/pfsensesetup.com\/pythonscript.net\/wp-json\/wp\/v2\/posts\/81\/revisions"}],"predecessor-version":[{"id":82,"href":"http:\/\/pfsensesetup.com\/pythonscript.net\/wp-json\/wp\/v2\/posts\/81\/revisions\/82"}],"wp:attachment":[{"href":"http:\/\/pfsensesetup.com\/pythonscript.net\/wp-json\/wp\/v2\/media?parent=81"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"http:\/\/pfsensesetup.com\/pythonscript.net\/wp-json\/wp\/v2\/categories?post=81"},{"taxonomy":"post_tag","embeddable":true,"href":"http:\/\/pfsensesetup.com\/pythonscript.net\/wp-json\/wp\/v2\/tags?post=81"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}