<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Arvind Hari on Medium]]></title>
        <description><![CDATA[Stories by Arvind Hari on Medium]]></description>
        <link>https://medium.com/@arvindhhp?source=rss-93362844bd1a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*rKBD58fsQjUWwsTE0pTSng.jpeg</url>
            <title>Stories by Arvind Hari on Medium</title>
            <link>https://medium.com/@arvindhhp?source=rss-93362844bd1a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 10:14:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@arvindhhp/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Happy Recursion]]></title>
            <link>https://medium.com/geekculture/happy-recursion-2519c0215caf?source=rss-93362844bd1a------2</link>
            <guid isPermaLink="false">https://medium.com/p/2519c0215caf</guid>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[recursion]]></category>
            <dc:creator><![CDATA[Arvind Hari]]></dc:creator>
            <pubDate>Sat, 03 Jul 2021 16:19:48 GMT</pubDate>
            <atom:updated>2021-07-03T19:12:20.604Z</atom:updated>
            <content:encoded><![CDATA[<p>The vicious yet unavoidable trap of Self Calls and Infinite Loops</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S0QYLSPY-HfVbpqEPkNE1g.jpeg" /><figcaption>Illusion (Uplash.com)</figcaption></figure><h3>Recursion</h3><p>We may come across situations involving looping where we do not know the number of iterations required. In such situations, we end up using While loops rather than for loops. Yet another way of dealing with this situation is “Recursion”.</p><p>In this article, I am sharing the basic recursion implementation using Python. I was bored of looking at Factorial examples here and there across the internet. So thought of implementing the same based on <strong>Happy Numbers</strong> (sounds so cheerful, right ? I too am smiling right now typing this).</p><h3>What is Recursion</h3><p>Recursion is a computer programming technique involving the use of a procedure, subroutine, function, or algorithm that calls itself in a step. Simple, right?</p><p>Well, re-read the definition, aren’t you feeling a bit uneasy on reading it?</p><p>Exactly, me too. If we create a function which calls itself, we will end up in an infinite loop. We do not want to be in this situation. To escape this vicious cycle, we need to provide some termination condition which on being met, the recursion will stop, and the final output gets delivered.</p><h3>Redefining Recursion</h3><blockquote>Recursion is a computer programming technique involving the use of a procedure, subroutine, function, or algorithm that calls itself in a step having a termination condition so that successive repetitions are processed up to the critical step where the condition is met at which time the rest of each repetition is processed from the last one called to the first. (Reference <a href="https://www.sparknotes.com/cs/recursion/whatisrecursion/section1/">Link</a>)</blockquote><p>Arghhh, too long to grasp right, let us take this up in a practical way. Let us try to solve a problem from number theory to understand better.</p><p>Let us try to find out, whether a given number is a HAPPY NUMBER or not.</p><h3>What is a HAPPY number ???</h3><p>If the sum of squares of its digits equals 1, the number is happy like 1, 10, 100 etc.</p><p>But the problem does not stop here, if the sum of square of the digits of the sum of square of the actual number equals 1, we can still call the original number happy.</p><p>For example, take 68, sum of squares is 6² + 8² = 36 + 65 = 100. But, continuing, sum of squares of 100 is 1² + 0 + 0 = 1. Hence, we can claim, 68 to be a HAPPY Number. I hope, you can smell the need of recursion here.</p><p>Well, let us try some different number, let us consider 11 for example, sum of squares is 2, sum of squares of 2 is 4, sum of squares of 4 is 16, sum of squares of 16 is 37, sum of squares of 37 is 58, sum of squares of 58 is 89, sum of squares of 89 is 145, sum of squares of 145 is 42, sum of squares of 42 is 20, <strong>AND SUM OF SQUARES OF 20 is 4</strong>…. And the whole thing keeps repeating. As we know, see, we already had 4 as sum of squares, we know 4 leads eventually back to 4, this will never reach 1.</p><p>This exactly can be used as our terminal condition to break the recursion. If for an entered number, the recursion results in repetition of sum of squares, exit the recursion.</p><p>With this, we can jump into the practical aspect of recursion. Please ensure you are comfortable with functions before going further.</p><blockquote><strong>A quick introduction to functions and return statements in Python, </strong><a href="https://www.linkedin.com/in/arvindhhp/"><strong>by myself</strong></a><strong>, </strong><a href="https://github.com/arvindhhp/PyPro_ahhp/blob/main/Part_007_Functions.ipynb"><strong>GitHub Link</strong></a><strong> 😆 😜</strong></blockquote><h3>Python Implementation</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/925155c9f2dc5bc6beaeb70ab2683470/href">https://medium.com/media/925155c9f2dc5bc6beaeb70ab2683470/href</a></iframe><h3><strong>What is the function doing ???</strong></h3><blockquote>Long story short, on line 13, the function happy_check() calls itself. But the only difference, with further calling, the argument gets updated as part of the previous lines executed within the function. And finally, we have the IF CONDITION takes care of the BASE CASE, which ensures the function is not called again when a certain condition is met.</blockquote><p>The complete code is available @ <a href="https://github.com/arvindhhp/PyPro_ahhp/blob/main/Part_018_Recursion.ipynb">GitHub</a></p><p>Congratulations, welcome to the world of recursion. Happy Recursion 😉</p><blockquote>Do follow me on <a href="https://www.linkedin.com/in/arvindhhp/">LinkedIn</a> and <a href="https://github.com/arvindhhp">GitHub</a> for more on Python and Data Science.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2519c0215caf" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/happy-recursion-2519c0215caf">Happy Recursion</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cassandra Connect]]></title>
            <link>https://medium.com/geekculture/cassandra-connect-99081b036c55?source=rss-93362844bd1a------2</link>
            <guid isPermaLink="false">https://medium.com/p/99081b036c55</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[nosql]]></category>
            <category><![CDATA[cassandra]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Arvind Hari]]></dc:creator>
            <pubDate>Mon, 28 Jun 2021 13:02:16 GMT</pubDate>
            <atom:updated>2021-06-28T13:02:16.561Z</atom:updated>
            <content:encoded><![CDATA[<p>Blending Cassandra with Python</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d7sRVmYd2vVRrCAgInRPuA.jpeg" /><figcaption>Image Credits: Upslash.com, Color Crescent</figcaption></figure><h3>What is Cassandra?</h3><p>Apache Cassandra™ is a distributed NoSQL database that delivers continuous availability, high performance, and linear scalability that successful applications require.</p><p>Apache Cassandra is an open source, distributed NoSQL database that began internally at Facebook and was released as an open-source project in July 2008. Cassandra delivers continuous availability (zero downtime), high performance, and linear scalability that modern applications require, while also offering operational simplicity and effortless replication across data centers and geographies. Cassandra can handle petabytes of information and thousands of concurrent operations per second, enabling organizations to manage large amounts of data across hybrid cloud and multi cloud environments.</p><p>DataStax have provided a fantastic outlook on the “What is” and “Why” of Cassandra. Follow the <a href="https://www.datastax.com/cassandra">link</a>.</p><p>However, it is indeed a subtly convoluted process to get started with Cassandra considering its installation itself takes some good time and efforts. In this article, I take you through this process step by step to install and ensure Cassandra is up and running in the local system. In addition, this article also gives a glimpse of using accessing the cloud version of Cassandra through DataStax. By the end of this article, I finally discuss configuring Cassandra-Python integration to perform the usual Database operations with Cassandra through Python.</p><p>So here we start.</p><h3>Cassandra Installation — Local System</h3><p>Cassandra Installation follows the sequence as:</p><p>· Java Installation (Version 8u202 or earlier)</p><p>· Cassandra Installation</p><p>· Python2 Installation (Cassandra-Python Integration demands Python2 to work seamlessly as of now)</p><p>· Apache Thrift Installation</p><h3>Java Installation</h3><p>Follow the <a href="https://www.oracle.com/in/java/technologies/oracle-java-archive-downloads.html">link</a>. Signing into Oracle is mandatory to progress. Please ensure, the version earlier than Java SE 8u202 is chosen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6DZ12-kqkl_bOwWHnVL1Ww.png" /><figcaption>Choose the Highlighted Java Version</figcaption></figure><p>Once, JAVA is downloaded, set up a new System Environment Variable JAVA_HOME. This should have the link to the Java folder downloaded.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/675/1*M6kqn0DFI4zlPR7nJ45glA.png" /><figcaption>JAVA_HOME System Variable Creation</figcaption></figure><h3>Cassandra Installation</h3><p>Follow the <a href="https://apachemirror.wuchna.com/cassandra/3.11.10/apache-cassandra-3.11.10-bin.tar.gz">link</a>.</p><p>Ensure, 7zip is installed in your system to handle the “. tar.gz” files.</p><p>Extract the folder from the download the “. tar.gz” file. Create another system variable, CASSANDRA_HOME with the link to the extracted folder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/676/1*xpxA_71sfiHLowh3Mb8NVw.jpeg" /><figcaption>CASSANDRA_HOME System Variable Creation</figcaption></figure><h3>Python 2 Environment</h3><p>Well, this is not mandatory, but I have observed this a few times myself and checked with some friends of mine, Cassandra encounters issues when we try to launch the CQL (Cassandra Query Language) through a Python 3 environment. So, it is advisable to create a Python 2 environment and try launching Cassandra from this Python 2 environment.</p><p>I have used Anaconda Prompt to get this done. I have created a Python 2 environment named Python2.</p><h3>Apache Thrift Installation</h3><p>Well, one the steps which is swift to perform.</p><p>Follow the <a href="https://apachemirror.wuchna.com/thrift/0.14.2/thrift-0.14.2.exe">link</a> and execute the ‘.exe’ file. This will flash within a second. No installation steps are involved, just execute the file.</p><p>With these 4 steps done, we are good to get started with Cassandra.</p><h3>Cassandra Query Language Execution</h3><p>Launch Command Prompt or Anaconda Prompt. Activate the Python 2 environment. It is advisable to launch the prompt in the admin mode. Change the directory to the bin folder within the Cassandra folder extracted.</p><p>I have placed the extracted Cassandra in my C drive, so the change directory command looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*RCu5aamoeTmaf8OJv19dyw.png" /></figure><p>On executing, “cassandra.bat -h”, we should get the message, Startup Complete as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*6dbvoilZ-OCWhQa9adQkNQ.png" /></figure><p>Once, this is done, keep this prompt open and launch a new prompt, repeat the steps to change the directory to bin. This time, execute ‘cqlsh’.</p><p>This is exactly how we jump into CQL, the CASSANDRA QUERY LANGUAGE. With successful execution, this is how the prompt should look like.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*nZrfqLdIZeAJV0esD0BPDQ.png" /><figcaption>CQL Setup in Local System Complete</figcaption></figure><p>Congratulations, Cassandra is up and running successfully in your local system as soon as you can notice the cqlsh&gt;</p><blockquote>It was long, wasn’t it, really time consuming and convoluted?</blockquote><p>Let us take the cloud path to reach this in no time.</p><h3><strong>Cassandra Through DataStax</strong></h3><p>DataStax, Inc. is a data management company based in Santa Clara, California. Its product provides commercial support, software, and cloud database-as-a-service based on Apache Cassandra. DataStax also provides event streaming support and a cloud service based on Apache Pulsar.</p><p>We can create a free account and use their services free of cost worth 25 dollars every month. For the purposes of within the scope of this article and understand Cassandra-Python integration, free version of DataStax is more than enough.</p><p>All we need to do is, create an account through the <a href="https://auth.cloud.datastax.com/auth/realms/CloudUsers/protocol/openid-connect/auth?client_id=auth-proxy&amp;redirect_uri=https%3A%2F%2Fgatekeeper.auth.cloud.datastax.com%2Fcallback&amp;response_type=code&amp;scope=openid+profile+email&amp;state=DCjl128Yg5gwCOgOIgkuNEyfoR8%3D">link</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZKk53K4XZLBDTIUXpkOhfA.png" /></figure><p>Once logged in, this is what we will be seeing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MO6zX-LnncJKyzo_On1eXQ.png" /></figure><p>Click on the Create Database option to proceed with it. Be wise and use the Free Version. I am emphasizing again, the free version is more than enough to get the job done for us.</p><p>Click on the Get Started button under “Start Free Now”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AlQFRez-5lpXkfyQ-4Sk0w.png" /></figure><p>Now comes the fun part, Cassandra has a slightly different architecture than other databases. Tables are not stored directly inside a database, rather they are stored in keyspaces. In other terms, a table is stored in a keyspace which is stored in a database. To understand more on what a keyspace is, how it differs from a table, follow the <a href="https://docs.datastax.com/en/astra/docs/db-glossary.html#_keyspace">link</a>.</p><p>Choose the cloud and region of your interest, it really does not matter, it is just a matter of luck, how quickly we can get our database created. As we are using shared services through free account, it takes some significant time (a few minutes) to get the Database created, initialised and provide the access.</p><p>IMPORTANT, Ensure the KEYSPACE names are completely <strong>lowercase</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*Zw5jVGq9wG3boVL91gV2xA.jpeg" /></figure><p>And, hurray, our new Cassandra Database is now ready. Wait until the Connect button gets activated. It takes a few minutes as we are working through shared servers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*bTsrIBUGsGR3tNbn6g9MMA.png" /></figure><p>Finally, it is time to access and play with Cassandra Databases through Python.</p><h3>CASSANDRA-PYTHON Integration</h3><p>We will start with discussing integrating the cloud version with Python, hold tight, a few steps process coming up. Cheers as it is a one-time activity per database.</p><p>As soon as we click on the new database and got to the Connect tab, we get to see the window as shown below. As we are trying to connect Cassandra with Python, select Python from the list of labels to the left. Then download the bundle from the Download Bundle option. Just download this and do nothing else yet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ewVRcaCsegxr0bAIVJp8EA.png" /></figure><p>Scroll down the page, and reach the bullet 4, which has a code snippet as shown below. This bunch of code is the key to connecting Cassandra with Python. Every single program through which, we are trying to reach the cloud version of Cassandra needs this piece of code. For every new database we create, a similar piece of code will be available.</p><p>All we need to do are:</p><p>· <strong>Import the CASSANDRA driver using !pip install cassandra-driver</strong></p><p>· Replace the &lt;&lt;/PATH/TO/&gt;&gt; with the folder location where the zipped bundle has been downloaded. Do not forget to place a backward slash (/) at the end of folder path.</p><p>· Replace the CLIENT ID and CLIENT SECRET with the corresponding tokens from the Token Management option. Just copy sand paste the ID and SECRET into the code.</p><blockquote>On executing the code, no errors should be encountered, especially, it should not return “An error occurred.” If so congratulations, we have successfully established the connection between cloud version of Cassandra and Python.</blockquote><p>All we need is, place the Cassandra Query within the execute().</p><p>To integrate the local version of Cassandra with Python, we do not need any authorisation. Hence, just ignore the lines related to cloud_config and auth_provider. Just call the Cluster(&lt;no args&gt;) and create a session.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*AE4jNxi_Tgkco_ju2W0ZsA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q55tDxNc45_H4c8JD75Itg.png" /></figure><blockquote><strong><em>Congratulations on CASSANDRA-PYTHON INTGEGRATION</em></strong></blockquote><p>More related articles on connecting Python to <a href="https://medium.com/geekculture/an-introduction-to-data-persistance-with-python-6c9b0364c4c9">MySQL </a>and <a href="https://medium.com/geekculture/nosql-database-handling-349176dc7be7">MongoDB</a></p><p>Do follow me on <a href="https://www.linkedin.com/in/arvindhhp/">LinkedIn </a>and <a href="https://github.com/arvindhhp">GitHub</a> for more on Python and Data Science.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=99081b036c55" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/cassandra-connect-99081b036c55">Cassandra Connect</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NoSQL Database Handling]]></title>
            <link>https://medium.com/geekculture/nosql-database-handling-349176dc7be7?source=rss-93362844bd1a------2</link>
            <guid isPermaLink="false">https://medium.com/p/349176dc7be7</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[digital]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Arvind Hari]]></dc:creator>
            <pubDate>Mon, 14 Jun 2021 20:14:35 GMT</pubDate>
            <atom:updated>2021-06-14T21:06:25.648Z</atom:updated>
            <content:encoded><![CDATA[<p>The Pythonic way of dealing with MongoDB</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ce0gUe0LbnhL7ebnDGTp5w.png" /><figcaption>Obviously, from the <a href="http://mongodb.com/">mongodb.com</a></figcaption></figure><p>SQL databases like MySQL, Oracle etc. follow a fixed schema per table. Schema refers to the number of columns and the type of data that is fed into the columns. Schema represents the structure of table with the SQL database. The issue with this approach is that, if we want to suddenly increase the number of columns, we need to create a whole new table altogether with the new structure. It is not very efficient to handle adhoc bulk amounts of data using SQL.</p><p>This is where, NoSQL (Not just SQL) databases come into picture. Here the schema is not a fixed entity. We can easily scale the data. Python provides facilities to deal with NoSQL databases directly. In this article, we discuss establishment of connection between Python and the NoSQL database MongoDB.</p><p><a href="https://ineuron.ai/">ineruon.ai</a> has come up with a very helpful <a href="https://github.com/arvindhhp/PyDB/blob/main/Ancillary_Files/MongoDB_Atlas.ipynb">article</a> to set up the the cloud version of MongDB known as ATLAS. In this article, we are using the free version of MongoDB ATLAS.</p><p>All the code snippets and their outputs are avaialble @ <a href="https://github.com/arvindhhp/PyDB/blob/main/Part_002_MongoDB_Python_Connection.ipynb">Github</a>.</p><h3>Establishing connection between Python and MongoDB</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0c81e978f108fecfe7a525eafa21b39f/href">https://medium.com/media/0c81e978f108fecfe7a525eafa21b39f/href</a></iframe><h3>Creating a Database and Collection in MongoDB</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a3b856006b4a9c791a4b1f432abebe14/href">https://medium.com/media/a3b856006b4a9c791a4b1f432abebe14/href</a></iframe><h3>Just an interim observation</h3><p>Unlike MySQL, an empty collection does not get created. See the image below. Collection is visible only when a record is entered.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/487/1*VFsZXmS1659Ux-EKdHEiiw.png" /><figcaption>Empty Cluster (even after adding a databse)</figcaption></figure><h3>Inserting a Record into a Collection</h3><p>The inputs are fed in terms of key-value pairs. We call it a JSON (Java Script Object Notation), but for the time being, let us just consider this a dictionary.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c48d66126d77eacd0717f37b9ccb0d6a/href">https://medium.com/media/c48d66126d77eacd0717f37b9ccb0d6a/href</a></iframe><h3>Unique ID</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/538/1*Ee6e-Zj8QQkcmDxlvZfNfg.png" /><figcaption>Auto created Unique ObjectIDs</figcaption></figure><blockquote>All the records are now visible iside the actual database in MongoDB ATLAS. Just showing one for simplicity.</blockquote><blockquote>_id is created automatically. This is unique per record. However, this can be manually over ridden. But within a collection, the user must ensure, all induvidual records have unique IDs</blockquote><h3>Overriding Unique _ids</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/90a6c88339463684b2b303a98cd02d42/href">https://medium.com/media/90a6c88339463684b2b303a98cd02d42/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/403/1*blK6b5wlfnmWZMpQNQU85Q.png" /><figcaption>User defined _id in MongoDB\</figcaption></figure><h3>Extracting data from MongoDB</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/89d4b37909e492666382c6949d87262b/href">https://medium.com/media/89d4b37909e492666382c6949d87262b/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f3e9ee931c1468aab99b0063fbb686a6/href">https://medium.com/media/f3e9ee931c1468aab99b0063fbb686a6/href</a></iframe><h3>Updating Data in MongoDB</h3><p>This can be achieved by passing two dictionaries to the update_many(old_dict,new_dict)</p><p>This function finds the first document (record) that matches with the query and update it with an object defining the new values of the document, i.e Updates a single record within the collection based on the filter.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/79213257deb5d1f8ba29ee3b95fc8c9f/href">https://medium.com/media/79213257deb5d1f8ba29ee3b95fc8c9f/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/387/1*BaSPMOtDMMCVVR5rCXZq5Q.png" /><figcaption>Updated data is now appended to the Collection’s Record</figcaption></figure><h4>Note the new data updated t the colelction that has _id : 1</h4><h3>Deleting Records (Documents) from a Collection</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2bacb1cecbde131191ffee6b278f7f1c/href">https://medium.com/media/2bacb1cecbde131191ffee6b278f7f1c/href</a></iframe><h3>Dropping a complete Collection</h3><p>We also have a ready made option to drop a complete collection from a database.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/73bd460d553dc05be2c76f9d36fe8df9/href">https://medium.com/media/73bd460d553dc05be2c76f9d36fe8df9/href</a></iframe><h3>Database with 2 collections Cars and Cars_Again before dropping</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/621/1*M4B3QySepdju6O6uuUNbpg.png" /></figure><h3>Database with just 1 collection Cars_Again after dropping</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/1*wwJC3ugCtgIFhwZWT_bExQ.png" /></figure><blockquote>So be it, welcome to the world of NoSQL databases</blockquote><blockquote>Signing off.</blockquote><blockquote>The code is available @ <a href="https://github.com/arvindhhp/PyDB/blob/main/Part_002_MongoDB_Python_Connection.ipynb">Github</a>. Do catch me on <a href="https://www.linkedin.com/in/arvindhhp/">Linkedin</a> for more.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=349176dc7be7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/nosql-database-handling-349176dc7be7">NoSQL Database Handling</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An Introduction to Data Persistance with Python]]></title>
            <link>https://medium.com/geekculture/an-introduction-to-data-persistance-with-python-6c9b0364c4c9?source=rss-93362844bd1a------2</link>
            <guid isPermaLink="false">https://medium.com/p/6c9b0364c4c9</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[mysql]]></category>
            <dc:creator><![CDATA[Arvind Hari]]></dc:creator>
            <pubDate>Sat, 12 Jun 2021 22:24:59 GMT</pubDate>
            <atom:updated>2021-06-14T16:19:15.891Z</atom:updated>
            <content:encoded><![CDATA[<p>Python in Database Management</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A0Jmch7ADkv6H4Q-8xckzw.jpeg" /><figcaption>Image Reference : <a href="https://wallpaperaccess.com/database">https://wallpaperaccess.com/database</a></figcaption></figure><h3>An Introduction to Python and Databases</h3><p>Almost every other computer application from a web based application to a simple desktop application stores and retrieves information from some persistent storage. This storage could be a local hard drive or a remote repository or anything. The reason why most recent computer applications are doing what they can is because they have the capability to access and modify data from such storage locations. Such a storage location could be simply termed as a “Database”.</p><p>Now, the type of data that is stored in the application could be in a structured form like tables in which the information in each column has some relation to the information in the other.</p><p>Some types of structured databases (SQL) are MySQL, Oracle, SQLite etc. Similarly, we can also have data stored in semi-structured form. Such types of databases are referred to as NoSQL (Not just SQL). Some types of NoSQL are MongoDB, Cassandra etc.</p><h3>Python in Database Management</h3><p>Well, we do have explicit ways to mess around with databases. We can learn SQL (Structured Query Language) or NoSQL (Not just SQL) to manage databases. Well, well, well, we also need different GUIs/ applications to access such databases. As usual, “Python” to the rescue. We can access databases and play with them directly using Python. All we need is to establish a connection between the Database server and Python. Then just execute the database queries as easy as eating a piece of cake from within Python.</p><p>In this introductory article, we try to understand how to establish a connection between a database server and Python. We are choosing MySQL, a form of structured database. The only requirement for us to proceed further is have MySQL workbench installed in our systems. MySQL workbench need to be kept open while working with MySQL through Python. This is essential as the MySQL server needs to be active whilst Python is trying to establish a connection.</p><p>All the code in this article with the outputs are are available in my <a href="https://github.com/arvindhhp/PyDB/blob/main/Part_001_MySQL_Python_Connection.ipynb">Github</a> repo along with the <a href="https://github.com/arvindhhp/PyDB/tree/main/Ancillary_Files">support files</a> used.</p><h3>Establishing Connection between Python and MySQL</h3><p>Python uses the “connector” method from “mysql” module to establish the connection.</p><p>In addition, we need the MySQL host name, MySQL user name and MySQL passoword to proceed.</p><p>This is available under Database — Connect Database. Password is the MySQL password set during installation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FSUbzTn0Pf-3ZtF--iuWrw.png" /><figcaption>MySQL Connection Options</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8118d11edb2ece444bf8a78e56a38856/href">https://medium.com/media/8118d11edb2ece444bf8a78e56a38856/href</a></iframe><h3>What does the code say …</h3><p>Line number 1 imports the necessary modules.</p><p>Line number 6 establishes the connection between MySQL and Python. The is_connection() method returns True if the connection gets established successfully.</p><p>Just like file operations, it is always good to close the DB connection once done using the close()</p><p>Simple, right?</p><h3>Creating a Database</h3><p>Let us try creating a MySQL database</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cfa13efbb484c5c8fa060b0a913742d9/href">https://medium.com/media/cfa13efbb484c5c8fa060b0a913742d9/href</a></iframe><h3>What does the code say …</h3><p>As usual, we start with establishing the connection with MySQL.</p><p>Now we step a bit ahead, we create a cursor. Cursor is basically created to capture the cursor’s position within the database as an when new queries get executed. In other terms, cursor is a pointer to the query.</p><p>Query is the actual SQL query used to achieve the action in MySQL</p><p>The cursor.execute() executes the query. Always remember, the queries should be in STRING format</p><p>Going forward, we just need to know what are the different queries.</p><p>Simple, right?</p><h3>Obtaining a list of existing Databases</h3><p>Now that we have created a new database, we should be able to see this in the list of databases available.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6dd8819f30032e0146c78e54eae471ac/href">https://medium.com/media/6dd8819f30032e0146c78e54eae471ac/href</a></iframe><h3>Creating a Table within a Database</h3><p>We are currently dealing with structured databases. The information in such databases are stored in forms of tables. One database can have multiple tables.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7839e9436f7dc4a4bd5508522a1b3eed/href">https://medium.com/media/7839e9436f7dc4a4bd5508522a1b3eed/href</a></iframe><h3>Cross Checking the updated Table using MySQL</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/398/1*QDGPWNkBFn1AjH9sxbxO4g.png" /><figcaption>Cross Checking with MySQL</figcaption></figure><p>As we can see, an empty table has been created in the Employee Database</p><h3>Inserting Values into Existing Tables</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f730a2538d5c67e5382f3893f52a5832/href">https://medium.com/media/f730a2538d5c67e5382f3893f52a5832/href</a></iframe><h3>Cross Checking the updated Table using MySQL again</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/478/1*H9SlKXJNqPnOsghp9FRKlA.png" /><figcaption>Cross Checking Update with MySQL</figcaption></figure><h3>Entering multiple lines of information to a Table</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dc7218a6881710c7e4f3f3114d17508a/href">https://medium.com/media/dc7218a6881710c7e4f3f3114d17508a/href</a></iframe><h3>Cross Checking the updated Table using MySQL again</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/482/1*BN_WoiVsvbieVTwA4y3skg.png" /><figcaption>Cross Checking Update with MySQL</figcaption></figure><h3>Entering multiple rows of data in one go …</h3><p>This can be achieved very easily using Pandas, but through conventional methods, if all the information is stored in a .csv file, we could enter a whole lot of information in one go.</p><p>If the data from external file is not in .csv format, we can convert it to .csv format</p><p>Thanks to ineuron.ai for this bit of code. Please ensure, there is a database “GlassData” exists before executing the code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6217a67c5b23b514fabf93e36cb05fab/href">https://medium.com/media/6217a67c5b23b514fabf93e36cb05fab/href</a></iframe><h3>Cross Checking the updated Table using MySQL again</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/483/1*7e3mZ38vYtZv9yDkb7r-3g.png" /><figcaption>Cross Checking wiy MySQL</figcaption></figure><blockquote>So, welcome to the world of Structured Databases with Python. Congratulations !!!</blockquote><p>All the code in this article are available in <a href="https://github.com/arvindhhp/PyDB/blob/main/Part_001_MySQL_Python_Connection.ipynb">Github</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6c9b0364c4c9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/an-introduction-to-data-persistance-with-python-6c9b0364c4c9">An Introduction to Data Persistance with Python</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Object Orinted Thinking : Operator Overloading and Polymorphism]]></title>
            <link>https://medium.com/geekculture/object-orinted-thinking-operator-overloading-and-polymorphism-3b7c91089693?source=rss-93362844bd1a------2</link>
            <guid isPermaLink="false">https://medium.com/p/3b7c91089693</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[polymorphism]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[object-oriented]]></category>
            <dc:creator><![CDATA[Arvind Hari]]></dc:creator>
            <pubDate>Sun, 06 Jun 2021 08:48:37 GMT</pubDate>
            <atom:updated>2021-06-18T14:30:31.774Z</atom:updated>
            <content:encoded><![CDATA[<h3>Object Oriented Thinking : Operator Overloading and Polymorphism</h3><p>Even the operators need to take up additional responsibilites</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uCeN4vlJflFbS1ATti1MQw.jpeg" /><figcaption>Overloaded (<a href="https://www.123rf.com/">https://www.123rf.com/</a>)</figcaption></figure><p>First of all, welcome to the last sector of the Introduction to Python Programming for Non-tech professionals’ series. I am excited to write this article and I am guessing you too are excited to read this. We have come quite a long way. The best part is, we get to end this series with a relatively easier and common concept.</p><p>All the codes snippets provided in this code and the outputs are stored in my <a href="https://github.com/arvindhhp/PyPro_ahhp/blob/main/Part_017_Operator_Overloading_Polymorphism.ipynb">Github repository</a>.</p><h4>Chuck the fancy terms, let us first try to contemplate on what overloading means?</h4><p>Some entity is overloaded when it is asked to perform more than it is supposed to. The entity has been assigned to perform some actions, which are pre-defined but due to certain additional requirements, some additioanl actions are falling onto its head. Just like a responsible and accountable professional like you at times get over loaded with work as and when new responsibilities are picked up.</p><p>Well, the same things can happen to operators also. As per mathematics, the plus sign (addition operator), ‘+’, is supposed to add two numbers. But what if, we define a certain method implementation within a class that forces the plus sign to multiply two inputs. Sounds weird, right?? But here I am just trying to give a feel of what operator over loading is. We will look at the practical aspects soon enough.</p><h4>What about Polymorphism then?</h4><p>Yet another very common term which just refers to the art of capability of some entity to take up various forms. Well, let me consider myself as an entity, I am a fluid system analyst when working, a lazy human on weekends, a student trying to communicate Python while writing this article etc., get it ?? We ourselves display the concept of polymorphism on a daily basis.</p><p>Similarly, in programming, we can have the same objet perform differently at different instances. For example, the same method defined within a class can produce different return values for different arguments, sounds obvious, but this is just polymorphism being displayed. Another example, let us go back to the plus sign, the addition operator (+), as we discussed above, ignore the operator overloading part, just think about the plus sign we all know. It can performs arithmetical addition for numerical inputs, string concatenation for string inputs, list appending for list inputs, fascinating, isn’t it ??</p><p>Exactly, that is how Python implements Polymorphism.</p><p>Yes, I can guess the thought itching your mind, we could simply consider, OPERATOR OVERLOADING is just a form of POLYMORPHISM where we specify what the operator should do. We will talk more about this soon.</p><p>Let us jump into OPERATOR overloading then.</p><h3>Operator Overloading</h3><h4>First things first</h4><p>To exploit the feature of operator overloading, we need to use the in-built method implementation of the particular operator. We just perform a METHOD OVERRIDING here. As we are aware, all the user defined classes, all the methods defined inside it, whatever be it, all become a part of THE ‘main’ class by default.</p><p>In simpler terms, all the user defined classes become subclass of the master class ‘main’.</p><p>Let me just show a sample of the same.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9c694417f41bc3298c37ae2d4423313e/href">https://medium.com/media/9c694417f41bc3298c37ae2d4423313e/href</a></iframe><p>Did you notice the output, how the ‘dummy’ class has been represented. It has been respresented as a subclass of the inbuilt class main.</p><p>Well, why are we talking about this operator overloading ??</p><p>The default functionalities of all the operators are defined within this ‘main’ class. When we redefine the implementation of any of the OPERATOR using a method inside one of the user defined sub classes, we are just OVER RIDING its implementaion locally within this method.</p><p>It is slightly tricker to understand the implementation though. The updated operator implementation can be utilised by performing the desired operations between two class objects.</p><p><strong>Let us implement it now for the addition operator (+)</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/88f53b4c7734ebdceb935e8f9158b733/href">https://medium.com/media/88f53b4c7734ebdceb935e8f9158b733/href</a></iframe><blockquote>‘ I completely accept, many of you might be lost right now, behold, it will make sense soon enough’</blockquote><p>In case, the <strong>add</strong> method was not re-implemented, a simple (+) between the Object1 and Object2 would result in an TypeError. This is absolutely understandable. We ar trying to two instances of some user defined class. The addition operaion does not have a role here. On performing such additions, the interpreter will intimate us that we are using the + operator with unsupported operands.</p><p>But here, we are over riding the pre-defined definition. We are now telling, if two objects of this class are added, please implement whatever the return statement of the <strong>add</strong>() within this class returns.</p><p>Always remember, this can be performed only for two objects of the same class which has the in-built function modified. The number of objects involved in this operation depends on the operation, arithmetic operations like add, divide, multiply etc. are binary opeations (with 2 operands), hence two objects. The same idea can be extended to comparison, assingment and even unary operators.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/87096ba22940e78acce3e41fb600dc99/href">https://medium.com/media/87096ba22940e78acce3e41fb600dc99/href</a></iframe><p>Quick reference for a list of available in-built implementations of various operators</p><p><a href="https://www.geeksforgeeks.org/operator-overloading-in-python/">Operator Overloading in Python - GeeksforGeeks</a></p><h3>Polymorphism</h3><p>Well, there is nothing much to discuss further here. But let me just show one simple method implementation that takes two arguments and retunrs the result of addition operation.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b00768621e01f1a94671de8d44d76b02/href">https://medium.com/media/b00768621e01f1a94671de8d44d76b02/href</a></iframe><h3>Congratulations</h3><p>We have made it this far.</p><p>In case, you have been following the complete series of Introductory Python for Non-Tech engineers, I would say, we have captured all the basics of Python standard I/O to various data types to loops to functions to file handling or directory handling to logging to exception handling and finally basics of OOPs concepts.</p><p>The complete repo @ <a href="https://github.com/arvindhhp/PyPro_ahhp">https://github.com/arvindhhp/PyPro_ahhp</a></p><p>The basic idea behind me presenting this sequence is to enable core engineers like MechEs, CivilEs and other professions irrespective of domain who have less to perform basic programming so that the power of Data can exploited through Machine Learning, complex data visualizations to enhance the existing capabilities.</p><p>With the understanding of the Python programming concepts covered in this series, we can consider ourselves to be eligible to go ahead and learn the art of exploiting data.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3b7c91089693" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/object-orinted-thinking-operator-overloading-and-polymorphism-3b7c91089693">Object Orinted Thinking : Operator Overloading and Polymorphism</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Object Oriented Thinking : Multiple Inheritance]]></title>
            <link>https://medium.com/geekculture/object-oriented-thinking-multiple-inheritance-c782c1d64b8?source=rss-93362844bd1a------2</link>
            <guid isPermaLink="false">https://medium.com/p/c782c1d64b8</guid>
            <category><![CDATA[oop-concepts]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[inheritance]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Arvind Hari]]></dc:creator>
            <pubDate>Tue, 01 Jun 2021 19:50:50 GMT</pubDate>
            <atom:updated>2021-06-15T12:55:48.197Z</atom:updated>
            <content:encoded><![CDATA[<h3>Object Oriented Thinking : Multiple Inheritance</h3><p>Tricky yet easy to understand, plethora of use cases though</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*WJp3dQ5xgiyPTMEkdz9LkQ.png" /><figcaption>Real World INHERITANCE</figcaption></figure><p>In the previous <a href="https://arvindhhp.medium.com/object-oriented-thinking-inheritance-ae912642de37">article</a>, I had touched upon the basic implementation of the OOPs concept of Inheritance in Python. The article also touched upon the idea of super() function.</p><p>In this notebook, I have dived a bit into depths of super(), MULTIPLE Inheritance and function OVER-RIDING.</p><p>Take a deep breath and Brace youselves, get ready to dive into Inheritance. Happy Inheritance (:</p><p><a href="http://realpython.com/">realpython.com</a>, Thanks again for some thoughtful insights.</p><h3>Ideology of MULTIPLE INHERITANCE</h3><p>In simple inheritance, we have ONE CHILD class inheriting information from ONE PARENT CLASS. It is a 1 to 1 relation. But in case of INHERITANCE, ONE CHILD class inherits information from TWO OR MORE PARENT classes.</p><p>Pictorially, this is how they look. The left link, represents SIMPLE Inheritance while the right link merge represents MULTIPLE Inheritance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/279/1*0w9u5ohuZzlaruSLJteMUQ.png" /><figcaption>Multiple Inheritance (Image source: scientecheasy.com)</figcaption></figure><h3>What is super()</h3><p>Now, with the fundamental understanding of what inheritance, how it is implemented in Python (at least simple one) and the difference between SIMPLE and MULTIPLE inheritance, I strongly feel, you are in a good state to understand, what super() actually is ?</p><p>From a broader perspective, at a higher level, super() gives you access to methods in a superclass from the subclass that inherits from it.</p><p>super() without any appended functionalities returns a temporary object of the SUPER class (also known as PARENT class). This temporary object can then be used to call the methods of the SUPER class.</p><p>This is similar to the procedure of accessing the methods belonging to a class outside the class using .; here instead &lt;super()&gt;. is used to call the respective SUPER class of the CHILD class from within the CHILD class.</p><h3>super() in SIMPLE Inheritance</h3><h3>SUPER and CHILD Class Definition</h3><p>To understand this, let us consider a bunch of classes, where the ‘square’ class inherits from the ‘polygon’ class. Here, ‘polygon’ class is the SUPER class whereas ‘square’ class is the CHILD class. The code block below contains the definitions of SUPER and CHILD classes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/866/1*BSIBWY8ye5lLb0XxtjFi-g.png" /><figcaption>SUPER (PARENT) Class Definition</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/871/1*Z6K4JE-WdImNV3efkSJ3Vg.png" /><figcaption>Child Class Definition</figcaption></figure><h3>What is the super() doing ?</h3><p>In Line 41, the ‘square’ class definition above has an <strong>init</strong>() that has two parameters. First one ‘self’ is a pointer that points to the class itself. The next one is another parameter ‘sides’. Nothing new, just like any other <strong>init</strong>().</p><p>In Line 42, the expression, another <strong>init</strong>() is mentioned, but this time, this is a function call prefixed by super() through DOT notation.</p><p>We know that, super() returns the temporary object of the SUPER class of the CHILD class from where it is getting called. In this case, super() is called from ‘square’ class which is inherited from ‘polygon’ class. The expression in Line 42, calls the <strong>init</strong>() of the ‘polygon’ class. And correspondingly, we also need to ensure the correct arguments are supplied in line with SUPER class’s <strong>init</strong>() parameter definition.</p><p>super() is not restricted to just the <strong>init</strong>(), it can be used to call any method of the SUPER class from within the CHILD class</p><p>Simple, right ?? Now let us intialise the ‘square’ class and see what is happening.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/877/1*iuClFzh5SkQWTiUPlcrA2g.png" /><figcaption>super() and Simple Inheritance Execution</figcaption></figure><h3>More on super()</h3><p>Until now, we have been using super() parameter-less.</p><p>Well, it can take two optional parameters, the CHILD class whose SUPER class we are trying to reach and a pointer to the CHILD class itself.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/1*Shp_cjPOdr8i8ueP9CoQOw.png" /><figcaption>super() call with Arguments</figcaption></figure><p>super() can also be used to reach the higher PARENT classes by skipping levels.</p><p>To understand this better, let me define a SIMPLE Inheritance of 3 classes in sequence. This is also known as MULTI-LEVEL Inheritance</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/879/1*wsyf88oz4RsgozB9ov0y4A.png" /><figcaption>super() in Multi Level Inheritance</figcaption></figure><p>The ‘child’ class defined above is inherited from ‘parent’ which is inherited from ‘grand_parent’.</p><p>super() can also be used to call the gprnt_method() from grand_parent class. This can be achieved by passing ‘parent’ as the class name within the super()</p><p>This is handy when one of the methods of a higher level class is over-ridden in any of its child classes, but we want to access the pre-over ridden version of the method. Let us discuss one last concept of “method OVER-RIDING” before we go ahead and understand MULTIPLE Inheritance</p><h3>Method OVER-RIDING</h3><p>As name says, the concept is about overriding the method defined in a PARENT class through a child class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/874/1*0mtV6TImnl9iUAbNKdatKQ.png" /><figcaption>Method Over-Riding</figcaption></figure><h3>What just happened here ???</h3><p>‘child’class already has a child_method(). On definig a new method with same, the method of the SUPER Class gets overridden. Here, child_method defined inside the childs_child class overrides the orignal method defined in the ‘child’ class. Be careful, on doing this, any update done to the PARENT class method will not reflect for this over riding CHILD class and its downstream CHILD classes.</p><p>Bottom line, if super(,) is used, it will go ahead and call the method corresponding to the PARENT of this CHILD.</p><h3>MULTIPLE INHERITANCE</h3><p>And, finally, we are here, the last topic, Congratulations for making this far ;-)</p><p>As we had already discussed, in MULTIPLE inheritance, MUTLIPLE PARENTS share all their information to ONE CHILD.</p><p>Let us use a dummy set of classes to understand this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/877/1*aAL-DXIJy0Ur7YtZRPTALQ.png" /><figcaption>MULTIPLE INHERITANCE, PARENT(s) &amp; CHILD definition</figcaption></figure><p>Well, well, well, what did I just do in the code block above. Unfortunately, MULTIPLE INHERITANCE is slightly tricky. Unlike, SIMPLE inheritance, which has just one PARENT, using super() was pretty straightforward. But in case of MULTIPLE inheritance, we have multiple PARENTs. super() will follow what the METHOD RESOLUTION ORDER (MRO) says. MRO is just a list of classes that Python will refer when it comes across two methods with same name. And we all know, to initialize a class, we all use a class with the same name <strong>init</strong>()</p><p>By default, Python interpreter gives priorities in the sequence of PARENT class definition in the inheritance statement. See line 3 of the code block above. The ‘child’ class takes ‘mother’ as the FIRST PARENT class and ‘father’ as the SECOND PARENT class. Hence, the parameter-less super() will end up initialising the <strong>init</strong>() of ‘mother’ class.</p><p>Okay, but how I have mutliple parents here, what do I do to initialise the other PARENTS. super() with arguments comes to the rescue here. Just define super() with the PARENT class and its pointer itself as arguments which has already been initialised.</p><p>When any new classes are defined, all these are by default objects of the main SUPER class. Literally all the classes have some default PARENT. Once this is done, the interpreter will go and look for the next available <strong>init</strong>() in the main SUPER class which would be nothing but the second PARENT’s <strong>init</strong>(). Let us not get too much into this for now. Similarly, if the CHLD class has many parents, write super() statements by keeping on updating the argument CLASS name in sequential expressions.</p><p>Be careful, the same issue will pop up for all the methods. A good code should ensure, redundant names should not be used for the features of classes which are related to each other some way. In that case, the MRO will not affect us, only one method with the specified identifier will exist in the code.</p><h3>Exection of MUTLIPLE Inheritance</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/869/1*7xhL647OLPRbuK_lxDeMLw.png" /><figcaption>MULTPLE INHERITANCE execution</figcaption></figure><h3>Method Resolution Order (MRO)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/874/1*vNejMebWferIq_rBDg0bYg.png" /><figcaption>Method Resolution Order</figcaption></figure><h3>Some additional reading material on MULTIPLE INHERITANCE for the curious ones</h3><p>As always, <a href="https://stackoverflow.com/questions/9575409/calling-parent-class-init-with-multiple-inheritance-whats-the-right-way">stackoverflow</a> to the rescue.</p><h3><strong>Happy Coding, Happy Inheritance :)</strong></h3><p>The code is available in my Github <a href="https://github.com/arvindhhp/PyPro_ahhp/blob/main/Part_015b_OOP_Multiple_Inheritance.ipynb">repository</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c782c1d64b8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/object-oriented-thinking-multiple-inheritance-c782c1d64b8">Object Oriented Thinking : Multiple Inheritance</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Object Oriented Thinking — Inheritance]]></title>
            <link>https://arvindhhp.medium.com/object-oriented-thinking-inheritance-ae912642de37?source=rss-93362844bd1a------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae912642de37</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[inheritance]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[oop]]></category>
            <dc:creator><![CDATA[Arvind Hari]]></dc:creator>
            <pubDate>Mon, 31 May 2021 07:24:20 GMT</pubDate>
            <atom:updated>2021-06-03T21:25:04.637Z</atom:updated>
            <content:encoded><![CDATA[<h3>Object Oriented Thinking : Inheritance</h3><p>Diving into Simple Inheritance using Python</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*36W1pHnX_Ig9Okn2f8KmcA.png" /><figcaption>Inheritance, Image Source: tutorials.supunkavinda.blog</figcaption></figure><h3>Object Oriented Thinking : Inheritance</h3><p>In the previous <a href="https://arvindhhp.medium.com/object-oriented-thinking-db615a7f1c11">article</a>, I had introduced the thought process behind object oriented approach. The article also had brief discussions around classes, attributes, methods and objects.</p><p>In this notebook, I have touched upon the basic implementation of the OOPs concept of Inheritance in Python.</p><p>Take a deep breath, Happy OOPs, Happy Inheritance (:</p><p>Thanks to realpython.com for some thoughtful insights</p><h3><strong>Inheritance Ideology</strong></h3><p>Inheritance refers to the process of obtaining something from someone. Here the giver and taker usually belong to a hierarchical tree. A simple example of inheritance could be a child inheriting the hair color from a parent. Here the parent and child are obviously a part of the hierarchy, a family, parent is the giver and child is the taker.</p><p>The same can be translated to programming also. Here instead of hair color, one class can inherit information from the other class. The information could be the attributes or methods or both.</p><blockquote>In OOP terminologies, the source class from which the information is inherited is called as the ‘PARRENT’ class while the other class which inherits the information is called as the ‘CHILD’ class.</blockquote><p>The information transfer can happen through different paths, for example, one PARENT class to one CHILD class (simple inheritance), multiple PARENT classes to one CHILD Class (multiple inheritance), one PARENT class to many CHILD classes and so on.</p><p>In this notebook, we will focus on SIMPLE INHERITANCE to understand the basic inheritance concepts and then finally dive into MULTIPLE INHERITANCE.</p><h3>Why Inheritance ??</h3><p>Well, we were happy with functions and modules, then as an improvisation, we moved to OOPs using Classes and Objects to improve modularity of the code. Then we started using ‘Abstraction’ to hide unnecessary information from users.</p><p>Now why are we even bothering to learn about INHERITANCE ?</p><p>The ideology of classes and objects is to group similar entities under the same roof. Imagine, what if further subgrouping is possible where most of the information in the downstream groups are going to flow down from the top most class.</p><p>For example, we all know dogs, lions and bears fall into the category of animals. Based on what we previously discussed, I can use a class to describe the attributes and methods of an animal and then create further objects to capture different attribute values for dogs, lions and bears.</p><p>Now consider, I want to deal with different breeds of dogs. Does it really sound meaningful to have different objects for each breed of a dog from animal class. ?? Sounds a bit disturbing, right ??</p><blockquote>Inheritance to the rescue. I can create classes for dogs, lions and bears as CHILD classes of single PARENT animal class, then further downstream create CHILD class for each type of animal to get their breeds. When we do this, all the information passed on-to the PARENT animal class will be flowed down to all downstream CHILD classes, we avoid repeating the features addition.</blockquote><p>Advantage of inheritance is that, CHILD classes can always modify the inherited data and also extend the list of attributes and methods within them without impacting the PARENT class. Sounds meaningful, Yes ?? For me, it does (;</p><blockquote>Crisply speaking, CHILD classes can override or extend the attributes and methods of parent classes. In other words, CHILD classes inherit all of the PARENT’s attributes and methods but can also specify attributes and methods that are unique to themselves.</blockquote><p>Let us move into the Python part now…</p><h3>Simple Inheritance</h3><blockquote>As discussed, simple inheritance refers to the case where ONE CHILD class inherits information from ONE PARENT class.</blockquote><p>For the coding purposes, let us stick to basics of geometry and shapes.</p><h3>PARENT Class Specs</h3><p>The PARENT class ‘polygon’ takes just one argument as input from the user at the time of initialization, the number of sides of the polygon. it has two methods, one to get the length of all sides of the polygon, second to estimate the perimeter.</p><p>Input and perimeter functions are called from within the init(). Just a simple initialization of the class is enough to execute it.</p><p>PARENT class is just another class. Inheritance implementation starts only when a new class is defined as CHILD class to another PARENT class</p><h3>PARENT Class Definition</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VRUtapdGjkCLeAGnp-C76A.png" /><figcaption>PARENT Class Defintion</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f4JZUNxrT43OtbDDaERJmg.png" /><figcaption>PARENT Class Definition (Contd.)</figcaption></figure><h3>PARENT Class Initialization</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rTsrz0XkaJPOUgWcIV0ldw.png" /><figcaption>PARENT Class Initialization</figcaption></figure><h3>Simple Inheritance Implementation</h3><p>For any polygon, regardless of the number of sides (obviously greater than or equal to 3), the perimeter is the sum of length of each side. Why define different classes to achieve the same. A different object can do the job.</p><p>But let us consider the case of polygon area, we need different methods for different shapes. But, area calculation can be done using the same information provided. We do not need to take the pains of getting all the details again.</p><p>As you guessed rightly, I am going to inherit the polygon class into downstream CHILD classes for specific shapes.</p><h3>super() Quick Introduction</h3><p>Well, we need to understand what a super() is before we proceed with inheritance.</p><p>super() is the proxy function which returns the PARENT class of a particular CHILD class. We use super() to initialize the <strong>init</strong>() of the PARENT class from within the CHILD class.</p><p>super() does much more than just search the parent class for a method or an attribute. It traverses the entire class hierarchy for a matching method or attribute. If you aren’t careful, super() can have surprising results. We will discuss super() in detail before going into MULTIPLE INHERITANCE.</p><p>For the time being, to keep it simple, in case of SIMPLE INHERITANCE, where ONE CHILD class is inheriting information from ONE PARENT class, super(). will search for the specified method within the PARENT class.</p><h3>CHILD Class Definition</h3><p>The PARENT class is provided as an argument within the CHILD class definition.</p><h3>Key Points to Remember</h3><blockquote><strong>1) While defining the init() for the child class, ensure all the parameters required for the parent class as well as new ones defined for the CHILD class are available in the init() signature.</strong></blockquote><blockquote><strong>2) While calling the PARENT init() within the CHILD init() using the super(), supply the PARENT Class parameters obtained in point 1 as arguments to the PARENT class init()</strong></blockquote><p>For example, Consider the following PARENT class init() signature is defined as : def _ _init _ _ (self, parameter1, parameter2)</p><p>CHILD Class needs additional information, say, parameter3</p><p>CHILD class definition should be as follows:</p><p>class CHILD(PARENT): def _ <em>init</em> <em>(self, parameter1, parameter2, parameter3): super().</em> <em>init</em> _(self, parameter1, parameter2)</p><p>Refer, code blocks for the actual syntax</p><h3>Sample code snippet for Inheritance</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YFfUimYw_VuHgQE_Y40-og.png" /><figcaption>Sample Inheritance Code</figcaption></figure><h3>Actual Child Class Definition</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YFOJsNEp-boZog80oVqdrw.png" /><figcaption>CHILD Class Definition, ‘square’ class inherits information from ‘polygon’ class</figcaption></figure><h3>What is the CHILD class doing ?</h3><p>As we are all aware, square is just another polygon which has 4 sides. I would love to use the methods and attributes of this polygon to get the length of input sides and calculate the perimeter without repeating the code. Hence, I have inherited the information from ‘polygon’ class into the ‘square’ class.</p><p>Notice, the area estimation class is a newly defined class that is added to the CHILD class. Area formulations are different for different shapes, remember ??</p><p>This area estimation class does not explicitly initialize new variables for the number of sides, length of each side and the perimeter. All we do is just initialize the PARENT polygon class from within the CHILD class using super().</p><p>Let us see, if the story I told holds good or not !!</p><blockquote>‘In the expression below, ‘4’ argument which gets passed into the polygon.__init__() through the super().__init__()</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ydKrujk4dsM_IQHMsHPy9Q.png" /><figcaption>Inheritance DEMO</figcaption></figure><p><strong>Congratulations, SIMPLE INHERITANCE has been successfully implemented</strong></p><blockquote><strong>The complete code is available @ </strong><a href="https://github.com/arvindhhp/PyPro_ahhp/blob/main/Part_015a_OOP_Simple_Inheritance.ipynb"><strong>GitHub</strong></a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae912642de37" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Object Oriented Conceptual Thinking : Abstraction]]></title>
            <link>https://medium.com/analytics-vidhya/object-oriented-conceptual-thinking-abstraction-57183c5e79a4?source=rss-93362844bd1a------2</link>
            <guid isPermaLink="false">https://medium.com/p/57183c5e79a4</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[object-oriented]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[abstract]]></category>
            <dc:creator><![CDATA[Arvind Hari]]></dc:creator>
            <pubDate>Sun, 30 May 2021 17:08:04 GMT</pubDate>
            <atom:updated>2024-03-08T04:45:40.343Z</atom:updated>
            <content:encoded><![CDATA[<h3>Object Oriented Thinking : Abstraction and Encapsulation</h3><p>Peaceful Swim on the banks of the Object Oriented Ocean</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/743/1*Sf7H5JMwynuE9zjJIJVLDQ.jpeg" /><figcaption>Abstraction, focus on what is necessary, Image from ideelart.com</figcaption></figure><h3>Object Oriented Thinking : Abstraction and Encapsulation</h3><p>In the previous <a href="https://arvindhhp.medium.com/object-oriented-thinking-multiple-inheritance-c782c1d64b8">article</a>, I had introduced the thought process behind inheritance and details on the implementaion of simple, multi level and multiple inheritance.</p><p>In this notebook, I have touched upon the basic implementation of the <a href="https://www.analyticsvidhya.com/blog/2020/09/object-oriented-programming/?utm_source=Backlink&amp;utm_medium=SEO"><strong>OOPs concepts</strong></a> of Abstraction and Encapsulation in <a href="https://www.analyticsvidhya.com/blog/2022/07/python-coding-interview-questions-for-freshers/?utm_source=Backlink&amp;utm_medium=SEO"><strong>Python</strong></a>. A few more shallow dives into other OOPs cocnepts to follow in the upcoming write-ups</p><p>Please note, all the gists of code in the article are embedded using the Github gists. To see the outputs, refer to the Jupyter notebook @ <a href="https://github.com/arvindhhp/PyPro_ahhp/blob/main/Part_016_OOP_Abstraction_Encapsulation.ipynb">Github Link</a></p><p>Happy OOPs (:</p><h3>Abstraction and Encapsulation Ideology</h3><p>The idea behind abstraction comes from the fact that only relevant data needs to be shared based on the requirement. Consider the situation, some guests are coming home and I plan to make some desert for all of us. I need some extra sugar, so I want this to be delivered to my house. All the shopkeeper needs to know is the quantity of sugar and the address of my house. He does not have any business in knowing why I need this much sugar and how I estimated this number. Here, I have just communicated what is necessary and relevant to the shopkeeper. This is the IDEA of Abstraction. Sensitive information, backend working methods, irrelevant data generated during the process of certain execution etc. need not be exposed to the user. We can implement the idea of ABSTRACTION to achieve this.</p><p>While implementing ABSTRATION, we create a common template object that acts as an interface and ensures only specific set of information gets transferred downstream. Like in the above case, the interface is the professional relationship between the shopkeeper and myself and the data shared is just the quantity of sugar and the delivery address. ABSTRACTION also comes into the picture of reusability of the code. Similar to the situation above, even Swiggy food delivery, amazon delivery and daily dairy supply need exactly the same type of inputs. This just means, a common template is applicable for all.</p><p>ABSTRACTION comes into the picture in OOP when an application is being developed by multiple users at different levels. One single person cannot remember all the details of this huge class, hence it is ensured only the relevant information that needs to be transferred are permitted to be accessed. And I am already guessing, the idea of ABSTRACTION is kind of clear in our minds right now. In Python, we can implement ABSTRACTION using a very simple and intuitive concept of ABSTRACT CLASS. We will discuss about this soon.</p><p>Food for thought, let us try to contemplate the fact: <strong>Do all of us really know how does a simple print(‘Hello’) works ?? Computers do not even understand anything other than 0s and 1s. Some smart minds have ensured, this print(‘Hello’) is understood well by the computer and ensured we do not need to go through all these hardships by exposing us to overwhelming information. This is a classic example of “ABSTRACTION implementation.”</strong></p><p>On the other hands, the concept of wrapping attributes and methods within a class and revealing only relevant and necessary information is known as ENCAPSULATION. The idea here is to keep the attributes, i.e. the data and the methods to be implemented on this data under the same roof, i.e a class. Basically, the moment we are using a class/object we are stepping into ENCAPSULATION.</p><p>The hidden detail is that, as a developer, we might have defined certain attributes whose values get dynamically updated during the code execution. We really do not want any external agent to mess around with such information accidentally. But also at the same time, we cannot keep this data inaccessible at all. What if someone genuinely needs to update one such attribute.</p><p><strong>The whole process of wrapping all the attributes and its methods in a single class and then safeguarding them from accidental access and also allowing additional mechanisms to enable access to the restricted members under one roof is known as ENCAPSULATION.</strong></p><p>Attribute security can be achieved by making the variables PUBLIC, PROTECTED or PRIVATE based on the requirements. To allow access to the restricted members, we can use something called as setter() and getter() functions. We will discuss about these later in the article.</p><h3>ABSTRACT CLASS</h3><p>An abstract class can be considered as a blueprint for other classes. It allows you to create a set of methods that must be created within any child classes built from the abstract class.</p><p>The ABSTRACT class only defines empty methods (also called as ABSTRACT METHODS), it just provides the template for its child classes to define their implementation. For example, based on the example above w.r.t ‘type of product’, ‘quantity’ and ‘address’, ABSTRACT class will only define empty functions to get these inputs, it won’t implement how and from where these inputs need to be fetched. It must be defined in the child classes only. This is done so that any modular change in any of the downstream definitions won’t affect the other objects. For example, what if the SWIGGY requires additional information of Google Map location to your house in addition to the address, but others do not need it, we can modify the implementation just within the Swiggy class.</p><p>A few points to remember while creating an ABSTRACT Class:</p><p>1) Needs Key-word ABC (stands for Abstract Base Class)</p><p>2) The empty implementations of ABSTRACT METHOD need to be started with the <strong>decorator @abstractmethod</strong></p><p>3) Child Class inheriting the Abstract Base Class must mandatorily define the implementation of all the abstract methods</p><p>4) ABC cannot be instantiated. Python denies ABC object creation.</p><p>If an object is created for an ABC, there are chances, we will have access to the empty abstract methods defined. Hence, Python ensures, ABC cannot be instantiated.</p><p>Let us try to replicate the above example of delivery to seal our understanding.</p><p>Please note, the details of decorators are not discussed in this article. For the time being, let us remeber this from a syntax perspective.</p><p>For more information on decorators, please refer: <a href="https://www.geeksforgeeks.org/decorators-in-python/">https://www.geeksforgeeks.org/decorators-in-python/</a></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c9ef2b6a28aaa7f70d57e99c27352ef4/href">https://medium.com/media/c9ef2b6a28aaa7f70d57e99c27352ef4/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cdb1910e939987281102135968b76f3d/href">https://medium.com/media/cdb1910e939987281102135968b76f3d/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/80f5a512dd8f7918f7f51c13402e1374/href">https://medium.com/media/80f5a512dd8f7918f7f51c13402e1374/href</a></iframe><h3>ENCAPSULATION</h3><p>Well, we have already discussed the ideology. We will incrementally understand the different types of access restrictions that can be applied to the attributes of class. We will end the article with a simple class implementing setter() and getter() in a class used for accessing and modifying a private variable.</p><h3>Public, Protected and Private Variables</h3><p>Public, Protected and Private are the restrictions that can be applied to any attribute within the class that defines its accessibility.</p><p>Public attributes/variables are those that can be accessed anywhere using the dot notation (obviously) Protected attributes/variables can be accessed only within the package Private attributes/variables can be accessed only within the class Usually, in OOP languages, we use keywords like Public or Private to define the scope. But in Python, we use single underscore and double underscore preceding the attribute name that signifies whether the attribute is PROTECTED or PRIVATE respectively. In Python, ABSTRACTION is not as stringent as in other OOP languages. The creator of Python felt that, every individual has the right to access all the variables, hence, private variables can also be accessed outside of the class. We will see in the code snippet below how this can be achieved.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1ae47ea9038a841c3fbf0fb023630147/href">https://medium.com/media/1ae47ea9038a841c3fbf0fb023630147/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6f95f966a1b0d0977a95670a729df066/href">https://medium.com/media/6f95f966a1b0d0977a95670a729df066/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/adcf43c1fa438fe98ee822913321f32e/href">https://medium.com/media/adcf43c1fa438fe98ee822913321f32e/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V1LE9H33hmBWZPAiXKMvkQ.png" /><figcaption>Private Attribute Access Issue</figcaption></figure><h3>Comments on Private Variable</h3><p>We can see, the inbuilt <strong>str</strong>() was able to access the Private attribute but when the same is being accessed from outside the class, using the dot notation, we come access Attribute Error exception. This is happening because, the private variables are hidden.</p><h3>Accessing Private Variables outside the Class</h3><p>Accessing can be achieved by addressing the class as well as object of the class in the dot notation while calling the private variable.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1f15e38a705b2b7f8b234e747837e9d5/href">https://medium.com/media/1f15e38a705b2b7f8b234e747837e9d5/href</a></iframe><h3>Modifying Private Variable outside the Class</h3><p>Modifying the private variable from regions outside the class be achieved by using the setter function.</p><h3>Using getter () and setter() Functions</h3><p>A separate method need to be defined within the class that takes an argument to extract or assign the a new value to the private variable from within the class.</p><p>Method defined to extract the desired private variable from outside the class is known as getter()</p><p>Method defined to update the value of private variable from outside the class is known as setter()</p><p>Remember, setter() and getter() are user defined functions. And these are not keywords, we can use any name. The whole point here is about the purpose of reaching the private attributes. As private attributes can be easily accessed from within the class, we define such methods within the class itself.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b2d74c9a8f5794e3f6ddcd4250f21ad2/href">https://medium.com/media/b2d74c9a8f5794e3f6ddcd4250f21ad2/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ed5511ec9af1c8a9301428b5da8d4781/href">https://medium.com/media/ed5511ec9af1c8a9301428b5da8d4781/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A9gGkNvjZZ2RdBI5XiBOSQ.png" /><figcaption>ENCAPSULATION Output</figcaption></figure><p>This concludes our basic discussion on ABSTRACTION and ENCAPSULATION using Python.</p><p>The code is available @ <a href="https://github.com/arvindhhp/PyPro_ahhp/blob/main/Part_016_OOP_Abstraction_Encapsulation.ipynb">Github</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=57183c5e79a4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/object-oriented-conceptual-thinking-abstraction-57183c5e79a4">Object Oriented Conceptual Thinking : Abstraction</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Object Oriented Thinking]]></title>
            <link>https://arvindhhp.medium.com/object-oriented-thinking-db615a7f1c11?source=rss-93362844bd1a------2</link>
            <guid isPermaLink="false">https://medium.com/p/db615a7f1c11</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[class]]></category>
            <category><![CDATA[objects]]></category>
            <category><![CDATA[object-oriented]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Arvind Hari]]></dc:creator>
            <pubDate>Sat, 29 May 2021 17:23:12 GMT</pubDate>
            <atom:updated>2021-05-29T17:23:12.732Z</atom:updated>
            <content:encoded><![CDATA[<h3>An Intro to OOPs</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/703/1*Zzc_D-baYOHuvQ1nbQplLQ.png" /><figcaption>Image Source: <a href="https://codezen.io/">https://codezen.io/</a></figcaption></figure><p>Considering the rise in usage of data science pan industries irrespective of the domain, the audience targeting to learn basics of programming to inherit data science and ML in their daily life is increasing. This article aims at throwing some light on the ideology of ‘What is Object Oriented approach’, understanding its basic deployment using Python.</p><p>I myself being a core MechE, I have myself endured quite a bit of challenges understanding programming. In this article, I have stressed on the aspects of “Objective Oriented” approach so that we can absorb this and exploit it for our daily lives.</p><p>As big and scary the name is, the concept is as easy (but vast) to understand and implement… All we need here is to understand the purpose of OOP</p><h3>A warm welcome to all to the world of OOP.</h3><p>Until now we were wandering around in the world of SCRIPTING, where the code is written directly without any representation of the real world entities and their inter-relationships. But now, we would be doing things in a more realistic way, the PYTHON way. Luckily we are working with Python which supports scripting as well OOPs.</p><h3>Ideology behind OOP</h3><p>Before we start, let us try to answer ourselves, what comes to our mind when we hear the cars, laptops, animals, sports etc.</p><p>For example, as soon as I hear CAR, my mind pictures a closed body with 4 wheels, 4 doors, corresponding windows with an engine that can move. This is a generic descriptions of what a car is, what are its attributes, what are its functions etc. However, different brands, different models, different makes, different versions of car exists which have their own inherent differences of all the attributes mentioned above. But the features (feature names, a wheel is generally called a wheel regardless of the car under consideration) of a car remains same. In addition to the features, cars have certain behaviors like it can move either in forward or backward direction at a time, it can run with or without AC, impact of AC on mileage, max steering capacity based on speed or something.</p><p>In the example above, CAR is the class of objects while number of doors, number of wheels, brand etc. are the features of this class object. Similarly, features of different cars can be defined using the features of a common car by just updating the corresponding values. The behaviors of the car is defined as the methods of the class object.</p><p>In a similar way, analogically, we can construct our program in a fashion that can group certain similar objects (objects with similar features and methods) under a specific category called a CLASS. For example, when 2 variables ‘a’ and ‘b’ are assigned values ‘hey’ and ‘hello’ respectively, which are strings, python interprets this as two different objects of the string class. This is exactly why we get error while typecasting strings to numerical as strings do not have the inherent behavior or method to apply this transformation. These are inbuilt classes, we can also define user defined classes to meet our application requirements.</p><p>A class is a blueprint for how something should be defined. It doesn’t actually contain any data. While the class is the blueprint, an instance is an object that is built from a class and contains real data. An instance of the CAR class is not a blueprint anymore. It’s an actual CAR with attributes like cost, brand mileage etc.</p><p>In summary, the idea behind OOP is to capture the features and behaviors of an object under the same software object called CLASS. Put another way, object-oriented programming is an approach for modeling concrete, real-world things, like cars, as well as relations between things, like companies and employees, students and teachers, and so on. OOP models real-world entities as software objects that have some data associated with them and can perform certain functions.</p><h3>Advantage of OOP over Scripting</h3><p>A few advantages to start with include, it improves the reusability of the code, supports modularity, makes the code more representative of real world, allows definition of relations between multiple entities.</p><p>Well, these are the same words we used while defining functions, then during module creation and now with OOP, it just keeps getting better and better. When we used functions, we were automating stuff within the same code, when the same functions were defined as modules, it could be used in any code, but now when we use OOPs, the whole bunch of feature variables and their corresponding functionalities or behaviors can be described using a single object. Different objects with similar features can use the features and methods from the common class already defined.</p><p>The verbosity ends for now, let us jump into a simple code snippets to understand what a class is, what its attributes and methods are. By the end of this article, we will try to understand how relations between two objects can be established using OOPs.</p><h3>Class Definition</h3><figure><img alt="Class defintion syntax" src="https://cdn-images-1.medium.com/max/723/1*_LJGz6w4K91RIXqFp89wZQ.png" /><figcaption>Class Definition : <a href="https://github.com/arvindhhp/PyPro_ahhp/blob/main/Part_014_OOP_Introduction.ipynb">https://github.com/arvindhhp/PyPro_ahhp/blob/main/Part_014_OOP_Introduction.ipynb</a></figcaption></figure><h3>Defining Multiple Objects for the same class</h3><p>As we discussed, the idea of using objects is to group similar instances under the same class. In the prev example, we defined the attributes of Audi Q7 (random values used for the sake of understanding attributes)</p><p>In a same way, different objects with CAR class (diff arguments) can be assigned to new objects</p><p>Let us try to define Tata Nano and Toyota Fortuner (random values used for the sake of understanding attributes</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/707/1*BkLE87BV-0BaqbzI2mte-g.png" /><figcaption>Object Definition</figcaption></figure><p>Did you notice in the code above, three different cars, with same attributes could be created using different car objects but same attributes of the CAR class. Well, thanks to OOPs, our code looks much more modular and real-world oriented. All the attributes defined within the <strong>init</strong>() are called as Instance attributes as it can take different for different class objects. A class attribute can be defined outside of <strong>init</strong>(), this will have the same value for all the class instances created.</p><p>Remember that custom objects are mutable by default. An object is mutable if it can be altered dynamically.</p><p>Next, it is time to understand behavioral definition (methods definition) and its access.</p><h3>Class Object Description</h3><p>Whenever we just call the class identifier in the main code, a new instance of the class is created at a new memory location. This happens regardless of whether the instance is assigned to a new variable or not. The output usually shows the name of the class when class is called along with the memory address. But this information is not very helpful for the user.</p><p>We can use another inbuilt function __str__() which can be used to override the output when a class is called. We can customize the output using __str__(). Such inbuilt functions starting and ending with double underscores are called as dunder functions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/745/1*RzxkbV_hGKrFe6hhdJjTtw.png" /><figcaption>Describing Objects without __str__( )</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*lKc0F06RZiCLXGyu_vvZMQ.png" /><figcaption>Object Description CODE using __str__( )</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/1*63mY3knxUjNpReLYcq_IPA.png" /><figcaption>Object Description Output using __str__( )</figcaption></figure><h3>Comments on ‘self’</h3><h3>What does a ‘self’ variable do</h3><p>All the attributes initialised in the <strong>init</strong>() and the methods created are local and specific to the class within which they are defined. These methods and attributes have meaning only in the presence of the corresponding class. ‘self’ is a pointer that just refers to the class name by default at the time of initialisation. It is a positional argument.</p><p>The first argument passed at the time of class call or method call corresponds to the variable next to the ‘self’ pointer in the <strong>init</strong>() or method definition.</p><h3>What happens if we miss ‘self’</h3><p>‘self’ is not a keyword, it is just a positional argument, representing the pointer. In case, self definition is missed, python interpreter will consider the first variable defined in the parameter list as the pointer referring to the class. This will mess the downstream arguments’ positional assignments. We do not want this to occur.</p><p>Hence, we must always ensure a dedicated pointer is defined as the first position within all the methods of the class (dunder and user defined methods). This pointer name is local to the method, each method can have its own local pointer name. But when the attributes of the class are called from the specific method, local pointer name should be correspondingly used in the dot notation.</p><h3>Best Practice</h3><p>However, as a best practice, ‘<strong>self</strong>’ should be used across all the methods.</p><p>Example below recreates the car_3 class with replacements for the ‘self’ pointer name in all the methods (dunder and user def.). I am repeating, this is not advised, always use ‘self’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*uaoPHLWWdlPWKSwQnGRs0Q.png" /><figcaption>Demonstration of varying pointer names instead of ‘self’</figcaption></figure><p>With this, I am concluding the introduction to object oriented appraoch. See you all with an article on OOPs concepts</p><p>The jupyter notebook used has been checked into to my Github profile</p><p>JUPUYTER notebook with Intro to OOPs</p><p><a href="https://github.com/arvindhhp/PyPro_ahhp/blob/main/Part_014_OOP_Introduction.ipynb">https://github.com/arvindhhp/PyPro_ahhp/blob/main/Part_014_OOP_Introduction.ipynb</a></p><p>Github Profile:</p><p><a href="https://github.com/arvindhhp">arvindhhp - Overview</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=db615a7f1c11" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>