{"id":988,"date":"2021-07-30T10:13:14","date_gmt":"2021-07-30T09:13:14","guid":{"rendered":"https:\/\/thepythoncodingbook.com\/?page_id=988"},"modified":"2023-11-12T12:51:11","modified_gmt":"2023-11-12T12:51:11","slug":"object-oriented-programming","status":"publish","type":"page","link":"https:\/\/thepythoncodingbook.com\/object-oriented-programming\/","title":{"rendered":"7 | Object-Oriented Programming"},"content":{"rendered":"\n<hr class=\"wp-block-separator has-text-color has-alpha-channel-opacity has-background aligncenter is-style-wide\" style=\"background-color:#6d227a;color:#6d227a\"\/>\n\n\n\n<div class=\"wp-block-jetpack-markdown\"><p>In a previous Chapter, I defined programming as \u201cstoring data and doing stuff with the data\u201d. This definition is not the most technical and detailed definition you\u2019ll read, but it\u2019s still a very good one. You\u2019ve learned about both parts of this definition. You can store data using various data types, and you can perform actions with the data, primarily by using functions. <strong>Object-oriented programming<\/strong> merges these two into a single item.<\/p>\n<p>I\u2019ll get back to this merger a bit later. This topic brings along with it some new terminology, too. You\u2019ll soon read about classes, objects, instances, attributes, and a few more too. As I\u2019ve done previously in this book, I\u2019ll make sure to explain the concepts behind these terms as clearly as possible.<\/p>\n<p>Indeed, you\u2019ve already come across the term class. You\u2019ve been using classes since your first program in Chapter 1. Have a look at the following variables:<\/p>\n<\/div>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">>>> number = 10\n>>> name = \"Stephen\"\n>>> shopping_list = [\"Coffee\", \"Bread\", \"Butter\", \"Tomatoes\"]\n\n>>> type(number)\n&lt;class 'int'>\n>>> type(name)\n&lt;class 'str'>\n>>> type(shopping_list)\n&lt;class 'list'><\/pre>\n\n\n\n<div class=\"wp-block-jetpack-markdown\"><p>When you use the <code>type()<\/code> built-in function to display an object\u2019s data type, you\u2019re told that this is of <code>class 'int'<\/code> or <code>class 'str'<\/code> or whatever the name of the data type may be.<\/p>\n<p>If you reread the previous sentence, you\u2019ll also notice the use of the word \u2018object\u2019. You can see you\u2019ve also been using objects all the time! All will be clear by the end of this Chapter.<\/p>\n<h2>The Object-Oriented Programming Paradigm<\/h2>\n<p>First, let\u2019s have a quick word about philosophy. Object-oriented programming is one of several <strong>programming paradigms<\/strong> or styles of programming. Whereas the tools you have learned about so far are unavoidable in most modern programming, object-oriented programming is a style of programming that you can use if you wish. However, there are some applications where it may be hard to avoid this paradigm.<\/p>\n<p>If you search on the internet\u2013a dangerous place to be most of the time\u2013you\u2019ll find a vast range of views about object-oriented programming, or OOP. Some love it. Others hate it. But if you don\u2019t get dragged into these philosophical debates about programming, you\u2019ll find that object-oriented programming is a great tool to have in your toolbox that you can choose to use on some occasions and avoid in other cases.<\/p>\n<p>Python is inherently an object-oriented programming language. However, you\u2019ll often see Python described as a multi-paradigm language. This means that it\u2019s a language that supports many different programming styles, including object-oriented programming.<\/p>\n<h2>Meet The Market Seller<\/h2>\n<p>That\u2019s enough about the theory of object-oriented programming for the time being. Let\u2019s work our way towards what object-oriented programming is.<\/p>\n<p>In this Chapter, you\u2019ll use the example of a market seller who\u2019s been learning Python and who decides to write code to help him deal with his daily operations of selling items at the market stall. You\u2019ve already met the market seller in Chapter 5 when you read about errors and bugs.<\/p>\n<p>He has four items on sale in this small stall. His first attempt at writing this code uses a number of lists:<\/p>\n<\/div>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">items = [\"Coffee\", \"Tea\", \"Chocolate\", \"Sandwich\"]\ncost_price = [1.1, 0.5, 0.9, 1.7]\nselling_price = [2.5, 1.5, 1.75, 3.5]\nstock = [30, 50, 35, 17]<\/pre>\n\n\n\n<div class=\"wp-block-jetpack-markdown\"><p>His next section prompts the user to enter the item sold and the quantity:<\/p>\n<\/div>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"6-9\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">items = [\"Coffee\", \"Tea\", \"Chocolate\", \"Sandwich\"]\ncost_price = [1.1, 0.5, 0.9, 1.7]\nselling_price = [2.5, 1.5, 1.75, 3.5]\nstock = [30, 50, 35, 17]\n\n# Input items and quantity sold\nitem_sold = input(\"Enter item sold: \").title()\nquantity = int(input(\"Enter quantity sold: \"))\nitem_index = items.index(item_sold)<\/pre>\n\n\n\n<div class=\"wp-block-jetpack-markdown\"><p>In this code, you\u2019ll note that you used the string method <code>title()<\/code> directly after the <code>input()<\/code> function. This is possible because <code>input()<\/code> returns a string. The <code>title()<\/code> method converts a string into title case. Try to run <code>&quot;this is a string&quot;.title()<\/code> in the Console to see what\u2019s the output.<\/p>\n<p>You\u2019ve already seen the need for changing the string returned from <code>input()<\/code> to a numeric format when you get the value for the quantity sold. You\u2019ve used the built-in function <code>int()<\/code> with the <code>input()<\/code> function as its argument.<\/p>\n<p>The list method <code>index()<\/code> returns the index that matches the item in the list. You can use this method to find the location of a specific item in the list.<\/p>\n<h2>The <code>+=<\/code> and <code>-=<\/code> Operators<\/h2>\n<p>Let\u2019s take a small detour before returning to the market seller\u2019s first attempt at this code.<\/p>\n<p>A common requirement in a program is to increment the value stored within a variable. For example, if you want to add to the score in a game, you can write:<\/p>\n<\/div>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">>>> score = 0\n>>> score = score + 1\n>>> score\n1<\/pre>\n\n\n\n<div class=\"wp-block-jetpack-markdown\"><p>There\u2019s a shortcut in Python for this operation which makes the code easier to write and more succinct:<\/p>\n<\/div>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">>>> score = 0\n>>> score += 1\n>>> score\n1<\/pre>\n\n\n\n<div class=\"wp-block-jetpack-markdown\"><p>The <code>+=<\/code> operator increments the value of the variable by the amount which follows the operator. The above code snippet is identical to the one before it.<\/p>\n<p>You can also decrease the value in a similar manner:<\/p>\n<\/div>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">>>> score = 0\n>>> score -= 5\n>>> score\n-5<\/pre>\n\n\n\n<div class=\"wp-block-jetpack-markdown\"><p>Other arithmetic operators work in the same way. You may want to experiment with <code>*=<\/code> and <code>\/=<\/code> as well, for example.<\/p>\n<h2>Market Seller\u2019s First Attempt<\/h2>\n<p>Let\u2019s look at the next section in the market seller\u2019s first attempt at writing the code:<\/p>\n<\/div>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"6,13-23\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">items = [\"Coffee\", \"Tea\", \"Chocolate\", \"Sandwich\"]\ncost_price = [1.1, 0.5, 0.9, 1.7]\nselling_price = [2.5, 1.5, 1.75, 3.5]\nstock = [30, 50, 35, 17]\n\ndaily_income = 0\n\n# Input items and quantity sold\nitem_sold = input(\"Enter item sold: \").title()\nquantity = int(input(\"Enter quantity sold: \"))\nitem_index = items.index(item_sold)\n\n# Work out required values\nprofit = quantity * (selling_price[item_index] - cost_price[item_index])\ndaily_income += selling_price[item_index] * quantity\n\n# Update stock\nstock[item_index] -= quantity\n# TODO Add check to make sure stock does not go below zero\n\nprint(profit)\nprint(daily_income)\nprint(stock[item_index])<\/pre>\n\n\n\n<div class=\"wp-block-jetpack-markdown\"><p>This works. The section headed with the comment \u2018Work out required values\u2019 works out the profit by subtracting the item\u2019s cost price from its selling price and multiplying that by the quantity sold. The next line increases the income for the day using the increment operator <code>+=<\/code> which takes the current value of <code>daily_income<\/code> and adds the income from this sale to it.<\/p>\n<p>The following section, which has the heading \u2018Update stock\u2019, updates the number of items in stock by using the decrement operator. The market seller also added a comment to remind him to add a bit more code later to check that the stock doesn\u2019t go below zero. Adding such a comment is a common technique to leave notes in your code for later on. Most IDEs also interpret the <code># TODO<\/code> comments differently from other comments, and the IDE will show you a to-do list using these comments.<\/p>\n<p>You can see the output from the test the market seller ran:<\/p>\n<\/div>\n\n\n\n<div class=\"wp-block-jetpack-markdown\"><pre><code class=\"language-console\">Enter item sold: chocolate\nEnter quantity sold: 7\n5.95\n12.25\n28\n<\/code><\/pre>\n<p>But the market seller stopped at this point as he realised that this might become quite cumbersome to deal with. Every operation will need to carefully reference the correct item in the correct list using the index. As the market seller adds more products and more information about each product, this method can quickly get out of hand.<\/p>\n<h4>Data that belong together<\/h4>\n<p>The code above stores the item\u2019s name, cost price, selling price, and stock quantity in separate variables. <em>You<\/em> know that these separate storage boxes \u201cbelong together\u201d and that each item in each list is related to the other items occupying the same position in the other lists.<\/p>\n<p>However, the computer program doesn\u2019t know that these data are related. Therefore, you need to ensure you make all of those links in the code. This style can make the code less readable and more prone to errors and bugs.<\/p>\n<h2>The Market Seller\u2019s Second Attempt<\/h2>\n<p>The market seller noticed the problem with having many lists which store the various attributes linked to each product. So, he decided to refactor his code and use dictionaries instead. <strong>Refactoring<\/strong> is the process of changing the code to make it neater and better without changing the overall behaviour of the code. Here\u2019s the market seller\u2019s refactored second attempt:<\/p>\n<\/div>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\"># Create dictionary with item names as keys and a list of numbers as the values. The\n# numbers in the lists refer to the cost price, selling price, and quantity in stock\n# respectively\nitems = {\n    \"Coffee\": [1.1, 2.5, 30],\n    \"Tea\": [0.5, 1.5, 50],\n    \"Chocolate\": [0.9, 1.75, 35],\n    \"Sandwich\": [1.7, 3.5, 17],\n}\n\ndaily_income = 0\n\n# Input items and quantity sold\nitem_sold = input(\"Enter item sold: \").title()\nquantity = int(input(\"Enter quantity sold: \"))\n\n# Work out required values\nprofit = quantity * (items[item_sold][1] - items[item_sold][0])\ndaily_income += items[item_sold][1] * quantity\n\n# Update stock\nitems[item_sold][2] -= quantity\n# TODO Add check to make sure stock does not go below zero\n\nprint(profit)\nprint(daily_income)\nprint(items[item_sold][2])<\/pre>\n\n\n\n<div class=\"wp-block-jetpack-markdown\"><p>You\u2019re now storing the data in a single dictionary instead of several lists. The keys in the dictionary are strings with the names of the items. The value for each key is a list. Each list contains the cost price, selling price, and the number of items in stock in that order.<\/p>\n<p>You may have already spotted one drawback. You need to reference the data in the lists using the index. Look at the following line as an example:<\/p>\n<\/div>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">profit = quantity * (items[item_sold][1] - items[item_sold][0])<\/pre>\n\n\n\n<div class=\"wp-block-jetpack-markdown\"><p>You first need to use one of the keys to extract a value from the dictionary <code>items<\/code>. The variable <code>item_sold<\/code> is the string that contains the name of the item.<\/p>\n<p><code>items[item_sold]<\/code> refers to the value of the <code>item_sold<\/code> key, which is a list. You\u2019re then indexing this to get one of the numerical values in the list. Therefore, <code>items[item_sold][1]<\/code> refers to the selling price of the item represented by the string <code>item_sold<\/code>. This makes the code harder to read and, for the same reason, more prone to errors.<\/p>\n<p>Using a single data structure to store all the data has its advantages. Adding a new item or removing one that\u2019s no longer sold is easier with the dictionary version than with the list approach. However, as the data structure becomes more complex, accessing items can also become trickier, leading to code that\u2019s harder to write, read, and maintain.<\/p>\n<h3>Adding Functions To Perform The Tasks<\/h3>\n<p>Before looking at yet another way of writing this code, you can add some functions to the code you have so far:<\/p>\n<\/div>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\"># Create dictionary with item names as keys, and a list of numbers as value. The\n# numbers in the lists refer to the cost price, selling price, and quantity in stock\n# respectively\nitems = {\n    \"Coffee\": [1.1, 2.5, 30],\n    \"Tea\": [0.5, 1.5, 50],\n    \"Chocolate\": [0.9, 1.75, 35],\n    \"Sandwich\": [1.7, 3.5, 17],\n}\n\ndaily_income = 0\n\ndef get_sale_info():\n    item_sold = input(\"Enter item sold: \").title()\n    quantity = int(input(\"Enter quantity sold: \"))\n    return item_sold, quantity\n\ndef get_profit(item_sold, quantity):\n    return quantity * (items[item_sold][1] - items[item_sold][0])\n\ndef update_income(item_sold, quantity):\n    return daily_income + items[item_sold][1] * quantity\n\ndef update_stock(item_sold, quantity):\n    items[item_sold][2] -= quantity\n    # TODO Add check to make sure stock does not go below zero\n\n# Call functions\nitem_sold, quantity = get_sale_info()\nprofit = get_profit(item_sold, quantity)\ndaily_income = update_income(item_sold, quantity)\nupdate_stock(item_sold, quantity)\n\nprint(profit)\nprint(daily_income)\nprint(items[item_sold][2])<\/pre>\n\n\n\n<div class=\"wp-block-jetpack-markdown\"><p>This code now puts all the functionality of the code into standalone functions. You\u2019ll recall the definition of programming I started the Chapter with. This code now clearly has the data stored in one variable and all the tasks that need to happen are defined as functions.<\/p>\n<p>Let\u2019s look at these functions a bit closer. The first one is <code>get_sale_info()<\/code>. This function asks the user to type in the product sold and how many of it were sold in a particular sale. The function returns a tuple with the values stored in <code>item_sold<\/code> and <code>quantity<\/code>. You\u2019ll recall that the parentheses are not needed to create a tuple, so the variable names in the <code>return<\/code> statement are not enclosed in brackets.<\/p>\n<p>The functions <code>get_profit()<\/code>, <code>update_income()<\/code>, and <code>update_stock()<\/code> all have two parameters. When you call these functions, the name of the item sold and the quantity sold need to be passed to the function.<\/p>\n<h4>Accessing global variables in functions<\/h4>\n<p>These three functions also use the data stored in the variable <code>items<\/code>. And <code>update_income()<\/code> also uses the data in <code>daily_income<\/code>. Functions have access to the global variables of the scope that\u2019s calling them. This means that when <a href=\"https:\/\/thepythoncodingbook.com\/understanding-programming-the-white-room\/\">Monty<\/a>, the computer program, goes to a Function Room, he can still use any of the boxes which are on the <a href=\"https:\/\/thepythoncodingbook.com\/understanding-programming-the-white-room\/\">White Room<\/a>\u2019s shelves.<\/p>\n<p>However, you can only ever use these functions with these variables. So, you may want to define the functions so that all the data needed is passed in as an argument and then returned when the function finishes its tasks. However, I won\u2019t make this change to this code as instead, I\u2019ll discuss the third option.<\/p>\n<h4>Changing the state of an object<\/h4>\n<p>You can notice another difference in the behaviour of these functions. The <code>update_stock()<\/code> function doesn\u2019t return anything as its only job is to change a value directly within the dictionary <code>items<\/code>. Dictionaries are mutable data types, and therefore this is valid. You may hear this referred to as <strong>changing the state<\/strong> of the object <code>items<\/code>.<\/p>\n<p>The other functions do not make any changes to existing variables directly. Instead, they return the new values, which you can then assign to variables when you call the functions, as you do in the section labelled \u2018Call functions\u2019 in the code.<\/p>\n<p>In this Chapter and the later Chapter on Functional Programming, you\u2019ll learn more about functions that change existing objects\u2019 state and others that do not.<\/p>\n<h2>Object-Oriented Programming<\/h2>\n<p>We\u2019ve gone a long way in this Chapter without having written any object-oriented code. Let\u2019s redress this now that you\u2019re familiar with the problems the market seller has encountered.<\/p>\n<p>When thinking with an object-oriented programming mindset, the starting point is to think of the main <strong>objects<\/strong> relevant to the problem you\u2019re solving. In a way, you need to think of the problem from a human being\u2019s perspective first and design your solution accordingly.<\/p>\n<p>Let\u2019s see what this means from the market seller\u2019s perspective. What are the objects that are relevant for the market seller? The objects that matter to him are the four products he sells. Although coffee, tea, chocolate, and sandwiches are different products with different prices and so on, they all share similar characteristics. They are all products that the market seller sells.<\/p>\n<p>You can therefore start by creating a class of objects in Python that describes these products.<\/p>\n<h2>Creating A Class<\/h2>\n<p>To create a <strong>class<\/strong> in Python, you can use the <code>class<\/code> keyword. You can create a new Python file called <code>market_stall.py<\/code> where you\u2019ll create your classes. If you choose a different file name, make sure you don\u2019t use any spaces in the file name:<\/p>\n<\/div>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">class Product:<\/pre>\n\n\n\n<div class=\"wp-block-jetpack-markdown\"><p>The convention is to use a capital letter for the name of a class. More generally, you should use upper camel case, such as <code>MyInterestingClass<\/code>.<\/p>\n<p>When you create a class, you\u2019re creating your own data type, one that\u2019s relevant for the application you\u2019re writing. The class definition that you\u2019ll be writing in the following sections acts as a template or a blueprint to create objects that belong to this class of objects.<\/p>\n<p>You\u2019ll see how to create an object of type <code>Product<\/code> soon, but first, we need to add a function definition within the class definition. A function that\u2019s a member of a class is called a <strong>method<\/strong>. Methods are functions, and therefore they behave in the same way as functions:<\/p>\n<\/div>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">class Product:\n    def __init__(self):\n        self.name = \"Coffee\"\n        self.cost_price = 1.1\n        self.selling_price = 2.5\n        self.number_in_stock = 30<\/pre>\n\n\n\n<div class=\"wp-block-jetpack-markdown\"><p>There\u2019s a lot to understand in this code. I\u2019ll explain all of the strange new additions in the following paragraphs.<\/p>\n<h3>The <code>__init__()<\/code> method<\/h3>\n<p>The <code>__init__()<\/code> method is a special function, and it\u2019s often the first part of a class definition. This method tells the program how to initialise a <code>Product<\/code> when you create one. When you create an object of type <code>Product<\/code>, the initial state of this object will be determined based on what happens in the <code>__init__()<\/code> method. <em>Hint:<\/em> if you just start typing \u201cinit\u201d in your IDE, the underscores and the parameter <code>self<\/code>, which you\u2019ll learn about soon, will autocomplete.<\/p>\n<p>Methods whose names start and end with double underscores have a special status and are often referred to as <strong>dunder methods<\/strong>. Dunder is a contraction of <strong>d<\/strong>ouble <strong>under<\/strong>score. Sometimes they\u2019re also called magic methods. However, there\u2019s nothing magical about them, so some prefer not to use that term.<\/p>\n<p>You\u2019ll have noticed another new term used in the <code>__init__()<\/code> method: <code>self<\/code>. I\u2019ll discuss <code>self<\/code> shortly as you\u2019ll see it a lot in class definitions.<\/p>\n<h2>Creating An Instance of A Class<\/h2>\n<p>When you defined the class in <code>market_stall.py<\/code>, you\u2019ve created a template for making products, but you haven\u2019t created any products yet. Let\u2019s create an <strong>instance<\/strong> of the class <code>Product<\/code> in the Python Console instead of in the script <code>market_stall.py<\/code>.<\/p>\n<p>When you start a Console session, you\u2019re creating a new White Room, which is separate from the one created when you run the <code>market_stall.py<\/code> script. Therefore, the Console\u2019s White Room doesn\u2019t know about the class <code>Product<\/code> yet. However, you can import your script in the same way you\u2019ve imported other modules previously:<\/p>\n<\/div>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">>>> import market_stall\n>>> market_stall\n&lt;module 'market_stall' from '\/&lt;path>\/market_stall.py'><\/pre>\n\n\n\n<div class=\"wp-block-jetpack-markdown\"><p>When you import a module, you\u2019re importing the contents of a Python script. This script could be one written by someone else or one you\u2019ve written yourself. You can see that the name <code>market_stall<\/code> in the Console session refers to the module, and it references the file. As with any module you import, you can now access anything from within this module. In this case, you can access the class <code>Product<\/code>.<\/p>\n<p>You can create an instance of the class <code>Product<\/code> as follows:<\/p>\n<\/div>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">>>> market_stall.Product()\n&lt;market_stall.Product object at 0x7f9178d61b20><\/pre>\n\n\n\n<div class=\"wp-block-jetpack-markdown\"><p>You can create an instance of a class by using the class name followed by parentheses. The output doesn\u2019t tell you much except that you\u2019ve created an object of type <code>Product<\/code> which is a part of the <code>market_stall<\/code> module. The memory address is also displayed, but you won\u2019t need this.<\/p>\n<p>You can assign this instance of the class to a variable name:<\/p>\n<\/div>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">>>> my_product = market_stall.Product()\n>>> my_product.name\n'Coffee'\n>>> my_product.selling_price\n2.5<\/pre>\n\n\n\n<div class=\"wp-block-jetpack-markdown\"><p>The name <code>my_product<\/code> now refers to the object you have created. When an instance of the class is created, the <code>__init__()<\/code> method is called. This means that every <code>Product<\/code> will always have a variable called <code>name<\/code> attached to it, and another one called <code>selling_price<\/code>. You can see the values of these instance variables displayed above. You can even access the other instance variables you have defined in the <code>__init__()<\/code> method in the same way.<\/p>\n<h4>Making the class more flexible<\/h4>\n<p>The problem with the code you have is that each product you create can only be coffee with the same cost price, selling price, and quantity in stock. You\u2019d like your class to be more general than this so that you can create other products as well.<\/p>\n<p>You can go back to <code>market_stall.py<\/code> and make some changes:<\/p>\n<\/div>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"4-8\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\"># market_stall.py\n\nclass Product:\n    def __init__(self, name, cost_price, selling_price, number_in_stock):\n        self.name = name\n        self.cost_price = cost_price\n        self.selling_price = selling_price\n        self.number_in_stock = number_in_stock<\/pre>\n\n\n\n<div class=\"wp-block-jetpack-markdown\"><p>Like any other function, <code>__init__()<\/code> can have parameters defined in its signature. The mysterious <code>self<\/code> was already there, but you\u2019ve now added more parameters.<\/p>\n<p>The arguments passed to the <code>__init__()<\/code> method are then <em>attached<\/em> to the instance. In the next section, we\u2019ll walk through what happens when you create an instance again, but this time you\u2019ll have to pass arguments when you create the instance.<\/p>\n<h4>Creating a new file to test the class definition<\/h4>\n<p>Rather than carrying on in the Console, you can now create a second file. Let\u2019s call this second script <code>market_seller_testing.py<\/code>. When dealing with object-oriented programming, it\u2019s common practice to define the classes in one file, or module, and then use these classes in other files:<\/p>\n<\/div>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\"># market_seller_testing.py\n\nfrom market_stall import Product\n\nfirst_prod = Product(\"Coffee\", 1.1, 2.5, 30)\nsecond_prod = Product(\"Chocolate\", 0.9, 1.75, 35)\n\nprint(first_prod.name)\nprint(second_prod.name)<\/pre>\n\n\n\n<div class=\"wp-block-jetpack-markdown\"><p>I\u2019ve included the file name as a comment at the top of each code block since you\u2019ll be working on two separate files from now on in this Chapter.<\/p>\n<p>You\u2019ve also used the <code>import<\/code> keyword differently from previous times. Instead of importing the whole module, you\u2019re now only importing one object from within that module. In this case, you\u2019re just bringing in the <code>Product<\/code> class and not the entire module. You can now use the class name <code>Product<\/code> without having to add <code>market_stall<\/code> and a dot before it.<\/p>\n<p>You created two instances of the class <code>Product<\/code>. The arguments you use within the parentheses are passed to the class\u2019s <code>__init__()<\/code> method. The objects <code>first_prod<\/code> and <code>second_prod<\/code> are both of type <code>Product<\/code>, and therefore they have been created using the same template. Both of them have instance variables called <code>name<\/code>, <code>cost_price<\/code>, <code>selling_price<\/code>, and <code>number_in_stock<\/code>. However, the values of these instance variables are different, as the output from the <code>print()<\/code> lines show:<\/p>\n<pre><code class=\"language-console\">Coffee\nChocolate\n<\/code><\/pre>\n<p>You can also confirm the data type of these two objects you have created:<\/p>\n<\/div>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"8-9\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\"># market_seller_testing.py\n\nfrom market_stall import Product\n\nfirst_prod = Product(\"Coffee\", 1.1, 2.5, 30)\nsecond_prod = Product(\"Chocolate\", 0.9, 1.75, 35)\n\nprint(type(first_prod))\nprint(type(second_prod))<\/pre>\n\n\n\n<div class=\"wp-block-jetpack-markdown\"><p>The output now shows that both objects are of type <code>Product<\/code>:<\/p>\n<pre><code class=\"language-console\">&lt;class 'market_stall.Product'&gt;\n&lt;class 'market_stall.Product'&gt;\n<\/code><\/pre>\n<p>When you create a class you\u2019re creating a new data type, one that you have designed to suit your specific needs.<\/p>\n<h4>Viewing two scripts side-by-side<\/h4>\n<p><em>A small practical note:<\/em> In most IDEs, you can split your window into multiple parts so that you can view two files side-by-side. Since you\u2019re defining your class in one file and testing it in a different file, this is a perfect time to explore some options in your IDE.<\/p>\n<p>If you\u2019re using PyCharm, you can look in the <em>Window<\/em> menu and choose the <em>Editor Tabs<\/em> option. You\u2019ll find the option to <a href=\"https:\/\/www.jetbrains.com\/help\/pycharm\/using-code-editor.html#split_screen\">split your screen<\/a> there. You can also make sure that any sidebars on the left-hand side are closed so that your screen is split between the two files.<\/p>\n<\/div>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-large\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"739\" height=\"214\" data-attachment-id=\"1016\" data-permalink=\"https:\/\/thepythoncodingbook.com\/object-oriented-programming\/ch7_split_screen\/\" data-orig-file=\"https:\/\/i0.wp.com\/thepythoncodingbook.com\/wp-content\/uploads\/2021\/07\/ch7_split_screen.png?fit=2798%2C808&amp;ssl=1\" data-orig-size=\"2798,808\" data-comments-opened=\"1\" data-image-meta=\"{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}\" data-image-title=\"ch7_split_screen\" data-image-description=\"\" data-image-caption=\"\" data-large-file=\"https:\/\/i0.wp.com\/thepythoncodingbook.com\/wp-content\/uploads\/2021\/07\/ch7_split_screen.png?fit=739%2C214&amp;ssl=1\" src=\"https:\/\/i0.wp.com\/thepythoncodingbook.com\/wp-content\/uploads\/2021\/07\/ch7_split_screen.png?resize=739%2C214&#038;ssl=1\" alt=\"Split screen setup in PyCharm IDE for object-oriented programming\" class=\"wp-image-1016\" srcset=\"https:\/\/i0.wp.com\/thepythoncodingbook.com\/wp-content\/uploads\/2021\/07\/ch7_split_screen.png?resize=1024%2C296&amp;ssl=1 1024w, https:\/\/i0.wp.com\/thepythoncodingbook.com\/wp-content\/uploads\/2021\/07\/ch7_split_screen.png?resize=300%2C87&amp;ssl=1 300w, https:\/\/i0.wp.com\/thepythoncodingbook.com\/wp-content\/uploads\/2021\/07\/ch7_split_screen.png?resize=768%2C222&amp;ssl=1 768w, https:\/\/i0.wp.com\/thepythoncodingbook.com\/wp-content\/uploads\/2021\/07\/ch7_split_screen.png?resize=1536%2C444&amp;ssl=1 1536w, https:\/\/i0.wp.com\/thepythoncodingbook.com\/wp-content\/uploads\/2021\/07\/ch7_split_screen.png?resize=2048%2C591&amp;ssl=1 2048w, https:\/\/i0.wp.com\/thepythoncodingbook.com\/wp-content\/uploads\/2021\/07\/ch7_split_screen.png?resize=1200%2C347&amp;ssl=1 1200w, https:\/\/i0.wp.com\/thepythoncodingbook.com\/wp-content\/uploads\/2021\/07\/ch7_split_screen.png?resize=1088%2C314&amp;ssl=1 1088w, https:\/\/i0.wp.com\/thepythoncodingbook.com\/wp-content\/uploads\/2021\/07\/ch7_split_screen.png?w=1478&amp;ssl=1 1478w, https:\/\/i0.wp.com\/thepythoncodingbook.com\/wp-content\/uploads\/2021\/07\/ch7_split_screen.png?w=2217&amp;ssl=1 2217w\" sizes=\"auto, (max-width: 739px) 100vw, 739px\" \/><\/figure>\n<\/div>\n\n\n<div class=\"wp-block-jetpack-markdown\"><p>If you\u2019re using other IDEs, you\u2019ll be able to find similar functionality, too.<\/p>\n<h2>Understanding <code>self<\/code><\/h2>\n<p>In the definition of the <code>__init__()<\/code> method, you\u2019ve used the keyword <strong><code>self<\/code><\/strong> several times. Let\u2019s start by looking at its use inside the function definition first. Here are the four lines in this definition that all reference <code>self<\/code>:<\/p>\n<\/div>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\"># ...\n        self.name = name\n        self.cost_price = cost_price\n        self.selling_price = selling_price\n        self.number_in_stock = number_in_stock<\/pre>\n\n\n\n<div class=\"wp-block-jetpack-markdown\"><p>The keyword <code>self<\/code> refers to the instance of the class that you\u2019ll create when you use the class. You read earlier that the class definition doesn\u2019t create any objects itself but serves as a blueprint for creating objects elsewhere in the code. The name <code>self<\/code> refers to the future name of the variable that the object will have.<\/p>\n<p>For example, in <code>market_seller_testing.py<\/code>, you created two variables named <code>first_prod<\/code> and <code>second_prod<\/code>. These variables each store a different instance of the class <code>Product<\/code>. You can think of the term <code>self<\/code> in the class definition as a placeholder for these names.<\/p>\n<p>Therefore, the above lines provide the instructions for the program to create four instance variables when it creates a new object. These lines are assignment statements, as shown by the <code>=<\/code> operator. The variables you\u2019re creating are <em>attached<\/em> to the instance. The dot between <code>self<\/code> and the variable name shows this link.<\/p>\n<p>An instance variable is a variable that is attached to an instance of a class. So every instance of the class you create will have its own instance variables <code>name<\/code>, <code>cost_price<\/code>, <code>selling_price<\/code>, and <code>number_in_stock<\/code>.<\/p>\n<h4>Creating the instance variables in the <code>__init__()<\/code> method<\/h4>\n<p>The <code>__init__()<\/code> method assigns values to the instance variables based on the arguments passed when creating the object. Recall that the values you place within parentheses when you create the instance of <code>Product<\/code> are passed to the <code>__init__()<\/code> method. The parameters <code>name<\/code>, <code>cost_price<\/code>, <code>selling_price<\/code>, and <code>number_in_stock<\/code> listed in the method\u2019s signature store the values passed when creating the instance.<\/p>\n<p>The parameter names and the instance variable names do not need to be the same name. Therefore, the following <code>__init__()<\/code> method is identical to the one you\u2019ve written above:<\/p>\n<\/div>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"4-8\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\"># market_stall.py\n\nclass Product:\n    def __init__(self, product_name, cost, sell, n_stock):\n        self.name = product_name\n        self.cost_price = cost\n        self.selling_price = sell\n        self.number_in_stock = n_stock<\/pre>\n\n\n\n<div class=\"wp-block-jetpack-markdown\"><p>The parameter names are only used to move information from the method call to the instance variables. Recall that the program calls the <code>__init__()<\/code> method whenever you create an instance of the class.<\/p>\n<h4><code>self<\/code> in the method signature<\/h4>\n<p>The other place you\u2019ve used <code>self<\/code> is as the first parameter in the <code>__init__()<\/code> signature. You may have noticed that your IDE probably auto-filled this for you when autocompleting <code>__init__()<\/code>. If you\u2019re not making the most of autocompletion in your IDE, then you should do so!<\/p>\n<p>This parameter tells the function that its first argument is the object itself. Therefore, the method has access to the object it is acting on. You\u2019ll see this used again in the following section when you create other methods for this class.<\/p>\n<h2>Adding Methods To The Class<\/h2>\n<p>So far, the <code>Product<\/code> class assigns instance variables to each instance of the class. Each product you\u2019ll create using the class <code>Product<\/code> will have a \u2018storage box\u2019 attached to it to store the product\u2019s name, another one to store the selling price, and so on.<\/p>\n<p>However, you can add more attributes to the class, and these are not limited just to data that can be stored in each object. You can also give the instances of the class the ability to do things as well. And as you know, \u201cdoing things\u201d is done by functions in Python:<\/p>\n<\/div>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"10-17\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\"># market_stall.py\n\nclass Product:\n    def __init__(self, name, cost_price, selling_price, number_in_stock):\n        self.name = name\n        self.cost_price = cost_price\n        self.selling_price = selling_price\n        self.number_in_stock = number_in_stock\n        \n    def decrease_stock(self, quantity):\n        self.number_in_stock -= quantity\n        \n    def change_cost_price(self, new_price):\n        self.cost_price = new_price\n        \n    def change_selling_price(self, new_price):\n        self.selling_price = new_price<\/pre>\n\n\n\n<div class=\"wp-block-jetpack-markdown\"><p>In addition to the <code>__init__()<\/code> method, you\u2019ve also defined three further methods. These functions are called methods as they belong to a class. Only objects of type <code>Product<\/code> will have access to these methods.<\/p>\n<h4>Using methods<\/h4>\n<p>Let\u2019s see how you can use these methods by going back to <code>market_seller_testing.py<\/code>:<\/p>\n<\/div>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"8-15\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\"># market_seller_testing.py\n\nfrom market_stall import Product\n\nfirst_prod = Product(\"Coffee\", 1.1, 2.5, 30)\nsecond_prod = Product(\"Chocolate\", 0.9, 1.75, 35)\n\nprint(f\"{first_prod.name} | Number in stock: {first_prod.number_in_stock}\")\nprint(f\"{second_prod.name} | Number in stock: {second_prod.number_in_stock}\")\n\nfirst_prod.decrease_stock(7)\n\nprint()\nprint(f\"{first_prod.name} | Number in stock: {first_prod.number_in_stock}\")\nprint(f\"{second_prod.name} | Number in stock: {second_prod.number_in_stock}\")<\/pre>\n\n\n\n<div class=\"wp-block-jetpack-markdown\"><p>In this version of the script, you\u2019re printing lines to show how many items there are in stock for each product you\u2019ve created. You then call the <code>decrease_stock()<\/code> method for <code>first_prod<\/code> with the argument <code>7<\/code>. When you print out the numbers in stock again, you\u2019ll see that the number of items in stock for <code>first_prod<\/code>, which is coffee, has decreased by <code>7<\/code>. However, the number of items in stock for <code>second_prod<\/code>, which is chocolate, remains unchanged since you didn\u2019t call the method for this object:<\/p>\n<pre><code class=\"language-console\">Coffee | Number in stock: 30\nChocolate | Number in stock: 35\n\nCoffee | Number in stock: 23\nChocolate | Number in stock: 35\n<\/code><\/pre>\n<p>This simple example shows one of the benefits of object-oriented programming. Once you\u2019ve defined the methods in the class, it becomes straightforward to keep track of which data belong to which object. If you look back at the first and second attempts the market seller made at the beginning of this Chapter, where he used lists and dictionaries, you\u2019ll recall that things weren\u2019t so easy there.<\/p>\n<p>Each object of a certain class has access to methods that will only act on that object. These methods will only change the data linked to that object.<\/p>\n<h4>Revisiting <code>self<\/code><\/h4>\n<p>Each method you\u2019ve created has <code>self<\/code> as the first parameter in the signature. You\u2019ll always call a method preceded by the object\u2019s name and a full stop, for example <code>first_prod.decrease_stock()<\/code>. The object itself is passed as the first unseen argument of the method <code>decrease_stock()<\/code>. Therefore the method call <code>first_prod.decrease_stock(7)<\/code> has two arguments and not just one. The first argument is <code>first_prod<\/code>, and the second is the integer <code>7<\/code>. However, you don\u2019t explicitly write the first argument as this is implied.<\/p>\n<p>You can confirm this with the following experiment in the Console (note, you should close your previous Console and restart a new one since <code>market_stall.py<\/code> has changed):<\/p>\n<\/div>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">>>> from market_stall import Product\n>>> test = Product(\"Coffee\", 1.1, 2.5, 30)\n>>> test.decrease_stock(4, 5)\nTraceback (most recent call last):\n  File \"&lt;input>\", line 1, in &lt;module>\nTypeError: decrease_stock() takes 2 positional arguments but 3 were given<\/pre>\n\n\n\n<div class=\"wp-block-jetpack-markdown\"><p>You\u2019ve tried calling <code>decrease_stock()<\/code> with the integers <code>4<\/code> and <code>5<\/code>. This is incorrect as this method only needs one integer. Therefore, the program raises an error. However, look at the last line of the error message very carefully. The message tells you that <code>decrease_stock()<\/code> takes <code>2<\/code> positional arguments because the method has two parameters in its signature. These two parameters are <code>self<\/code> and <code>quantity<\/code>. The error message also says that you passed <code>3<\/code> arguments, even though you only put two numbers in the parentheses. The three arguments you passed are <code>test<\/code>, <code>4<\/code>, and <code>5<\/code>.<\/p>\n<h4>One more method<\/h4>\n<p>Let\u2019s add one more method to this class. In <code>market_seller_testing.py<\/code>, you\u2019ve printed out a formatted string to show the user the number of items in stock for each product. Unless you enjoy typing, you had to copy and paste that line and change the variable name.<\/p>\n<p>However, this is something that an object of type <code>Product<\/code> should be able to do. You can do this by adding a method to the class whose job is to print out this formatted string:<\/p>\n<\/div>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"19-20\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\"># market_stall.py\n\nclass Product:\n    def __init__(self, name, cost_price, selling_price, number_in_stock):\n        self.name = name\n        self.cost_price = cost_price\n        self.selling_price = selling_price\n        self.number_in_stock = number_in_stock\n\n    def decrease_stock(self, quantity):\n        self.number_in_stock -= quantity\n\n    def change_cost_price(self, new_price):\n        self.cost_price = new_price\n\n    def change_selling_price(self, new_price):\n        self.selling_price = new_price\n\n    def show_stock(self):\n        print(f\"{self.name} | Number in stock: {self.number_in_stock}\")<\/pre>\n\n\n\n<div class=\"wp-block-jetpack-markdown\"><p>The method <code>show_stock()<\/code> doesn\u2019t make any changes to the object. It merely prints out the formatted string. You can compare the <code>print()<\/code> line in this method to the ones you wrote in <code>market_seller_testing.py<\/code> earlier. In the method, you\u2019ve now replaced the variable name with the keyword <code>self<\/code>, which is the placeholder for the name of the object.<\/p>\n<p>You can now also update <code>market_seller_testing.py<\/code> to use this new method:<\/p>\n<\/div>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"8,9,14,15\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\"># market_seller_testing.py\n\nfrom market_stall import Product\n\nfirst_prod = Product(\"Coffee\", 1.1, 2.5, 30)\nsecond_prod = Product(\"Chocolate\", 0.9, 1.75, 35)\n\nfirst_prod.show_stock()\nsecond_prod.show_stock()\n\nfirst_prod.decrease_stock(7)\n\nprint()\nfirst_prod.show_stock()\nsecond_prod.show_stock()<\/pre>\n\n\n\n<div class=\"wp-block-jetpack-markdown\"><p>You should spend some time experimenting with the methods you\u2019ve created, and you can even create one or two more!<\/p>\n<h2>Storing Data And Doing Stuff With Data<\/h2>\n<p>At the beginning of this Chapter, I described object-oriented programming as a way of merging the storage of data with doing stuff with data into one structure. There are two types of <strong>attributes<\/strong> that an object of a certain class can have:<\/p>\n<ul>\n<li><strong>instance variables<\/strong> such as <code>self.name<\/code>. These are also called <strong>data attributes<\/strong><\/li>\n<li><strong>methods<\/strong> such as <code>self.decrease_stock()<\/code><\/li>\n<\/ul>\n<p>The instance variables, like all variables, store data. These are the boxes we use to store information in. The methods do stuff with the data, as all functions do. Therefore an object contains within it both the data and the functions to perform actions on the data.<\/p>\n<p>In object-oriented programming, each object carries along with it all the data and the tools it needs. As you did with variable names and function names previously, it is best practice to name your instance variables using nouns and to start the name of your methods with a verb. And as always, descriptive names are better than obscure ones!<\/p>\n<h2>You\u2019ve Already Used Many Classes<\/h2>\n<p>You\u2019ve been using object-oriented programming for a very long time in your Python journey. Let\u2019s look at an example:<\/p>\n<\/div>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">>>> my_numbers = [5, 7, 3, 20, 1]\n>>> type(my_numbers)\n&lt;class 'list'>\n>>> my_numbers.append(235)\n>>> my_numbers\n[5, 7, 3, 20, 1, 235]<\/pre>\n\n\n\n<div class=\"wp-block-jetpack-markdown\"><p>In the first line, you\u2019ve created an instance of the class <code>list<\/code>. Since lists are one of the basic data types in Python, the way you create an instance looks different to how you\u2019ve created an instance of <code>Product<\/code>, but the process behind the scenes is very similar. An object of type <code>list<\/code> has access to several methods, such as <code>append()<\/code>, which act on the object and make changes to the object.<\/p>\n<p>When you define your own class, you\u2019re creating your own special data type that you can use in the same way you can use other data types.<\/p>\n<h2>Type Hinting<\/h2>\n<p>I\u2019ll make a slight detour in this section to briefly introduce a new topic. There is more information about this topic in one of the Snippets at the end of this Chapter.<\/p>\n<p>In Python, you don\u2019t need to declare what data type you will store in a variable. Python will decide what type of data you\u2019re storing depending on what you write in the assignment. This statement may seem obvious. However, there are programming languages that require the programmer to state that a specific variable will be an integer, say, before storing an integer in it. In these languages, once you declare the type of a variable, you cannot store any other data type in that variable.<\/p>\n<p>The same is valid for function definitions. Look at the following simple function:<\/p>\n<\/div>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">>>> def add_integers(a, b):\n...    return a + b<\/pre>\n\n\n\n<div class=\"wp-block-jetpack-markdown\"><p>It\u2019s clear from the function\u2019s name and how you\u2019ve written the function that your intention is that <code>a<\/code> and <code>b<\/code> are both numbers. You want <code>a<\/code> and <code>b<\/code> to be both of type <code>int<\/code>. However, your Python program doesn\u2019t know that. Both of these function calls are valid:<\/p>\n<\/div>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">>>> add_integers(5, 7)\n12\n>>> add_integers(\"Hello\", \"World\")\n'HelloWorld'<\/pre>\n\n\n\n<div class=\"wp-block-jetpack-markdown\"><p>Clearly, in the second case, you didn\u2019t add numbers, but Python knows how to \u2018add\u2019 two strings using the <code>+<\/code> operator, so it\u2019s not bothered that the arguments are strings and not integers. Only you know that <code>a<\/code> and <code>b<\/code> were meant to be numbers.<\/p>\n<p>A colleague you share this code with would also probably guess that <code>a<\/code> and <code>b<\/code> should be integers in this simple example. But this is not always the case.<\/p>\n<p>You can add hints in your code to let colleagues know what data type you\u2019re expecting the arguments to be:<\/p>\n<\/div>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"1\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">>>> def add_integers(a: int, b: int):\n...    return a + b<\/pre>\n\n\n\n<div class=\"wp-block-jetpack-markdown\"><p>Note that this does not force you to use integers as arguments. These are merely hints to assist programmers who are using this function. The call <code>add_integers(&quot;Hello&quot;, &quot;World&quot;)<\/code> will still work as it did earlier.<\/p>\n<h4>Other reasons to use type hinting<\/h4>\n<p>There are some other benefits of using <strong>type hinting<\/strong> other than helping other programmers who use your code. Many tools you use in programming will also understand these type hints and will warn you about transgressions. Have a look at the warning that PyCharm gives you when the you write the example above in a script:<\/p>\n<\/div>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-large\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"739\" height=\"344\" data-attachment-id=\"1026\" data-permalink=\"https:\/\/thepythoncodingbook.com\/object-oriented-programming\/ch7_type_hint_warning\/\" data-orig-file=\"https:\/\/i0.wp.com\/thepythoncodingbook.com\/wp-content\/uploads\/2021\/07\/ch7_type_hint_warning.png?fit=1106%2C514&amp;ssl=1\" data-orig-size=\"1106,514\" data-comments-opened=\"1\" data-image-meta=\"{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}\" data-image-title=\"ch7_type_hint_warning\" data-image-description=\"\" data-image-caption=\"\" data-large-file=\"https:\/\/i0.wp.com\/thepythoncodingbook.com\/wp-content\/uploads\/2021\/07\/ch7_type_hint_warning.png?fit=739%2C344&amp;ssl=1\" src=\"https:\/\/i0.wp.com\/thepythoncodingbook.com\/wp-content\/uploads\/2021\/07\/ch7_type_hint_warning.png?resize=739%2C344&#038;ssl=1\" alt=\"Type hinting warnings in PyCharm IDE\" class=\"wp-image-1026\" srcset=\"https:\/\/i0.wp.com\/thepythoncodingbook.com\/wp-content\/uploads\/2021\/07\/ch7_type_hint_warning.png?resize=1024%2C476&amp;ssl=1 1024w, https:\/\/i0.wp.com\/thepythoncodingbook.com\/wp-content\/uploads\/2021\/07\/ch7_type_hint_warning.png?resize=300%2C139&amp;ssl=1 300w, https:\/\/i0.wp.com\/thepythoncodingbook.com\/wp-content\/uploads\/2021\/07\/ch7_type_hint_warning.png?resize=768%2C357&amp;ssl=1 768w, https:\/\/i0.wp.com\/thepythoncodingbook.com\/wp-content\/uploads\/2021\/07\/ch7_type_hint_warning.png?resize=1088%2C506&amp;ssl=1 1088w, https:\/\/i0.wp.com\/thepythoncodingbook.com\/wp-content\/uploads\/2021\/07\/ch7_type_hint_warning.png?w=1106&amp;ssl=1 1106w\" sizes=\"auto, (max-width: 739px) 100vw, 739px\" \/><\/figure>\n<\/div>\n\n\n<div class=\"wp-block-jetpack-markdown\"><p>You\u2019ll still be able to run this code, but PyCharm has highlighted the string arguments in yellow, and when you hover on the yellow highlight, you\u2019ll get a pop-up window telling you that an <code>int<\/code> is expected. Other IDEs will also offer similar functionality.<\/p>\n<p>There\u2019s another advantage of using type hinting. As your IDE is now aware of the data type you want your parameters to represent, you can now use autocompletion when you type the parameter name followed by a dot.<\/p>\n<h2>Adding Another Class to Help The Market Seller<\/h2>\n<p>The market seller has now learned the philosophy of object-oriented programming. Therefore, he asked himself the question: <em>What are the objects that matter to me to run my market stall?<\/em><\/p>\n<p>The items he sells are important, and the <code>Product<\/code> class creates a data type that allows him to create products. However, that\u2019s not enough. The other object that matters to him is his till or cash register. The cash register is where he keeps his money and where he records his transactions. Let\u2019s help him create a new class:<\/p>\n<\/div>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"23-28\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\"># market_stall.py\n\nclass Product:\n    def __init__(self, name, cost_price, selling_price, number_in_stock):\n        self.name = name\n        self.cost_price = cost_price\n        self.selling_price = selling_price\n        self.number_in_stock = number_in_stock\n\n    def decrease_stock(self, quantity):\n        self.number_in_stock -= quantity\n\n    def change_cost_price(self, new_price):\n        self.cost_price = new_price\n\n    def change_selling_price(self, new_price):\n        self.selling_price = new_price\n\n    def show_stock(self):\n        print(f\"{self.name} | Number in stock: {self.number_in_stock}\")\n        \n        \nclass CashRegister:\n    def __init__(self):\n        self.income = 0\n        self.profit = 0\n        self.cash_available = 100<\/pre>\n\n\n\n<div class=\"wp-block-jetpack-markdown\"><p>You\u2019ve created the <code>CashRegister<\/code> class with its <code>__init__()<\/code> method. When you create an instance of the class <code>CashRegister<\/code>, you\u2019ll create three instance variables that all have a starting value. The market seller\u2019s code will create a <code>CashRegister<\/code> instance every morning when he opens his stall and runs his program.<\/p>\n<p>The instance variables <code>income<\/code> and <code>profit<\/code> have initial values of <code>0<\/code> as the market seller has not made any sales yet at the start of the day. He always starts the day with \u00a3100 in the cash register, so the <code>cash_available<\/code> instance variable is initialised with the value <code>100<\/code>.<\/p>\n<h3>Registering a sale<\/h3>\n<p>Let\u2019s look at what functions a cash register needs to perform. The main one is to register a sale whenever a customer comes along and buys an item.<\/p>\n<p>You can create a method for the <code>CashRegister<\/code> class with the following signature:<\/p>\n<\/div>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">def register_sale(self, item, quantity):<\/pre>\n\n\n\n<div class=\"wp-block-jetpack-markdown\"><p>The method has three parameters:<\/p>\n<ul>\n<li><code>self<\/code> is the first parameter that represents the object the method is acting on<\/li>\n<li><code>item<\/code> identifies what product is purchased, whether it\u2019s a coffee or a sandwich, say<\/li>\n<li><code>quantity<\/code> determines how many of the item were purchased in the transaction<\/li>\n<\/ul>\n<p><em>Question:<\/em> What data type would you choose for <code>item<\/code>?<\/p>\n<p>You could make <code>item<\/code> a string, for example <code>&quot;Coffee&quot;<\/code>. However, there\u2019s a better option.<\/p>\n<p><code>Product<\/code> is a data type and objects of this type can therefore be used as an argument for a function or method. By making <code>item<\/code> an object of type <code>Product<\/code>, you\u2019re making the most of all the data and functionality available in the <code>Product<\/code> class.<\/p>\n<p>To make this clearer, you can use type hinting in this method definition:<\/p>\n<\/div>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"29-34\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\"># market_stall.py\n\nclass Product:\n    def __init__(self, name, cost_price, selling_price, number_in_stock):\n        self.name = name\n        self.cost_price = cost_price\n        self.selling_price = selling_price\n        self.number_in_stock = number_in_stock\n\n    def decrease_stock(self, quantity):\n        self.number_in_stock -= quantity\n\n    def change_cost_price(self, new_price):\n        self.cost_price = new_price\n\n    def change_selling_price(self, new_price):\n        self.selling_price = new_price\n\n    def show_stock(self):\n        print(f\"{self.name} | Number in stock: {self.number_in_stock}\")\n\n\nclass CashRegister:\n    def __init__(self):\n        self.income = 0\n        self.profit = 0\n        self.cash_available = 100\n\n    def register_sale(self, item: Product, quantity: int):\n        sale_amount = quantity * item.selling_price\n        self.income += sale_amount\n        self.cash_available += sale_amount\n        self.profit += quantity * (item.selling_price - item.cost_price)<\/pre>\n\n\n\n<div class=\"wp-block-jetpack-markdown\"><p>The method signature now uses type hinting showing that <code>item<\/code> should be of type <code>Product<\/code> and <code>quantity<\/code> should be an <code>int<\/code>. The method then works out the sale amount using <code>quantity<\/code> and the <code>selling_price<\/code> instance variable of the item. Incidentally, type hinting means that we can be lazy (read: efficient) when coding as the IDE will autocomplete <code>item<\/code>\u2019s attributes since the IDE is aware that this variable is of type <code>Product<\/code>.<\/p>\n<p>The <code>register_sale()<\/code> method then updates the instance variables of the <code>CashRegister<\/code> object to increase the daily income and the cash available in the till. To work out the profit, you need to use both the item\u2019s cost price and selling price to get the profit from the sale of that item.<\/p>\n<h4>Testing the method<\/h4>\n<p>You can check that this method works by using it in <code>market_seller_testing.py<\/code>:<\/p>\n<\/div>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"8-19\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\"># market_seller_testing.py\n\nfrom market_stall import Product, CashRegister\n\nfirst_prod = Product(\"Coffee\", 1.1, 2.5, 30)\nsecond_prod = Product(\"Chocolate\", 0.9, 1.75, 35)\n\ntill = CashRegister()\n\nprint(till.income)\nprint(till.profit)\nprint(till.cash_available)\n\ntill.register_sale(second_prod, 5)\nprint()\n\nprint(till.income)\nprint(till.profit)\nprint(till.cash_available)<\/pre>\n\n\n\n<div class=\"wp-block-jetpack-markdown\"><p>You\u2019re now creating an instance of the class <code>CashRegister<\/code> and showing the data attributes before and after you call <code>register_sale()<\/code>. This code gives the following output:<\/p>\n<pre><code class=\"language-console\">0\n0\n100\n\n8.75\n4.25\n108.75\n<\/code><\/pre>\n<p>However, there\u2019s a bit more you can do in this method.<\/p>\n<h4>Updating the <code>Product<\/code> when registering a sale<\/h4>\n<p>You\u2019ve passed an object of type <code>Product<\/code> as an argument for the <code>CashRegister<\/code> method <code>register_sale()<\/code>. You can also update the number of items in stock of the product. If the market seller sold <code>5<\/code> chocolates in one transaction, then he has five fewer chocolates in stock.<\/p>\n<p>Let\u2019s add an extra line to the <code>register_sale()<\/code> method in the <code>CashRegister<\/code> class:<\/p>\n<\/div>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"34\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\"># market_stall.py\n\nclass Product:\n    def __init__(self, name, cost_price, selling_price, number_in_stock):\n        self.name = name\n        self.cost_price = cost_price\n        self.selling_price = selling_price\n        self.number_in_stock = number_in_stock\n\n    def decrease_stock(self, quantity):\n        self.number_in_stock -= quantity\n\n    def change_cost_price(self, new_price):\n        self.cost_price = new_price\n\n    def change_selling_price(self, new_price):\n        self.selling_price = new_price\n\n    def show_stock(self):\n        print(f\"{self.name} | Number in stock: {self.number_in_stock}\")\n\n\nclass CashRegister:\n    def __init__(self):\n        self.income = 0\n        self.profit = 0\n        self.cash_available = 100\n\n    def register_sale(self, item: Product, quantity: int):\n        sale_amount = quantity * item.selling_price\n        self.income += sale_amount\n        self.cash_available += sale_amount\n        self.profit += quantity * (item.selling_price - item.cost_price)\n        item.decrease_stock(quantity)<\/pre>\n\n\n\n<div class=\"wp-block-jetpack-markdown\"><p>And you can make a few changes in <code>market_seller_testing.py<\/code>, too:<\/p>\n<\/div>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"13,21\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\"># market_seller_testing.py\n\nfrom market_stall import Product, CashRegister\n\nfirst_prod = Product(\"Coffee\", 1.1, 2.5, 30)\nsecond_prod = Product(\"Chocolate\", 0.9, 1.75, 35)\n\ntill = CashRegister()\n\nprint(till.income)\nprint(till.profit)\nprint(till.cash_available)\nsecond_prod.show_stock()\n\ntill.register_sale(second_prod, 5)\nprint()\n\nprint(till.income)\nprint(till.profit)\nprint(till.cash_available)\nsecond_prod.show_stock()<\/pre>\n\n\n\n<div class=\"wp-block-jetpack-markdown\"><p>This gives the following output:<\/p>\n<pre><code class=\"language-console\">0\n0\n100\nChocolate | Number in stock: 35\n\n8.75\n4.25\n108.75\nChocolate | Number in stock: 30\n<\/code><\/pre>\n<p>You can see from the output that the program also decreased the number of chocolates in stock when you called <code>till.register_sale()<\/code>.<\/p>\n<p>Before finishing this Chapter, you should go back to the top and review the first and second attempts that the market seller made. These were the versions of the code that didn\u2019t use the object-oriented programming approach. Look at the code you wrote earlier on and compare it with the OOP version. You\u2019ll be able to appreciate that, once you\u2019ve defined the classes, using object-oriented programming leads to neater and more readable code in some projects. This will made developing your code quicker and less likely to lead to errors and bugs that may be hard to find.<\/p>\n<h2>Conclusion<\/h2>\n<p>In this Chapter, you\u2019ve learned about the object-oriented programming paradigm and the philosophy behind this topic. There are two reasons why you need to know the basics of object-oriented programming.<\/p>\n<p>Firstly, you may want to write your own classes for specific projects in which the investment you put into writing the class in the first place pays off when you write your application. Any classes you define, you can reuse in other projects, too.<\/p>\n<p>You also need to be familiar with classes and OOP because you\u2019ll come across many classes as you use standard and third-party modules in Python. Even though someone else has already written these classes, understanding the concept of classes and OOP will help you understand and use the tools in these modules.<\/p>\n<p>There\u2019s a lot more to say about object-oriented programming. The aim of this Chapter is to provide an introduction to the basics. I\u2019ll briefly discuss a couple of additional topics in the Snippets section at the end of this Chapter. However, a detailed study of OOP is beyond the scope of this book.<\/p>\n<p>In this Chapter, you\u2019ve learned:<\/p>\n<ul>\n<li>What is the <strong>philosophy<\/strong> behind object-oriented programming<\/li>\n<li>How to <strong>define a class<\/strong><\/li>\n<li>How to <strong>create an instance<\/strong> of a class<\/li>\n<li>What <strong>attributes, instance variables, and methods<\/strong> are<\/li>\n<li>How to <strong>define methods<\/strong><\/li>\n<\/ul>\n<p>You also learned about:<\/p>\n<ul>\n<li>The increment and decrement operators <code>+=<\/code> and <code>-=<\/code><\/li>\n<li>Type hinting<\/li>\n<\/ul>\n<p>In the next Chapter, you\u2019ll learn about <a href=\"https:\/\/thepythoncodingbook.com\/using-numpy-numerical-python-for-quantitative-applications\/\">using NumPy<\/a>, which is one of the fundamental modules that you\u2019ll use for quantitative applications.<\/p>\n<h5>Additional Reading<\/h5>\n<ul>\n<li><em>You can read more about instance variables and an alternative way of picturing them in the blog post about <a href=\"https:\/\/thepythoncodingbook.com\/2021\/08\/05\/python-instance-variables-and-kids-on-a-school-trip\/\">Python Instance Variables<\/a>.<\/em><\/li>\n<li><em>And you can try out another object-oriented project in which you\u2019ll <a href=\"https:\/\/thepythoncodingbook.com\/2021\/09\/09\/using-object-oriented-programming-in-python-bouncing-balls\/\">simulate bouncing balls<\/a><\/em><\/li>\n<li><em>And here\u2019s another project using object-oriented programming to <a href=\"https:\/\/thepythoncodingbook.com\/2022\/07\/02\/simulating-a-tennis-match-using-object-oriented-programming-in-python-wimbledon-special-part-1\/\">simulate a tennis match in Python<\/a><\/em><\/li>\n<\/ul>\n<\/div>\n\n\n\n<div class=\"wp-block-buttons is-horizontal is-content-justification-center is-layout-flex wp-container-core-buttons-is-layout-7d812b4c wp-block-buttons-is-layout-flex\">\n<div class=\"wp-block-button has-custom-width wp-block-button__width-50 is-style-outline is-style-outline--1\"><a class=\"wp-block-button__link has-text-color wp-element-button\" href=\"https:\/\/thepythoncodingbook.com\/using-numpy-numerical-python-for-quantitative-applications\/\" style=\"border-radius:3px;color:#00a0c1\">Next Chapter<\/a><\/div>\n<\/div>\n\n\n\n<div style=\"height:30px\" aria-hidden=\"true\" class=\"wp-block-spacer\"><\/div>\n\n\n\n<div class=\"wp-block-buttons is-horizontal is-content-justification-center is-layout-flex wp-container-core-buttons-is-layout-7d812b4c wp-block-buttons-is-layout-flex\">\n<div class=\"wp-block-button has-custom-width wp-block-button__width-75 is-style-fill\"><a class=\"wp-block-button__link has-text-color has-background wp-element-button\" href=\"https:\/\/thepythoncodingbook.com\/book-outline\/\" style=\"border-radius:3px;color:#0d363a;background-color:#fdb33b\">Browse Zeroth Edition<\/a><\/div>\n<\/div>\n\n\n\n<div style=\"height:30px\" aria-hidden=\"true\" class=\"wp-block-spacer\"><\/div>\n\n\n\n<p class=\"wp-block-paragraph\"><\/p>\n\n\n\n<div class=\"wp-block-group\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\"><\/div><\/div>\n\n\n\n<p class=\"wp-block-paragraph\"><\/p>\n\n\n\n<hr class=\"wp-block-separator has-text-color has-alpha-channel-opacity has-background aligncenter is-style-wide\" style=\"background-color:#6d227a;color:#6d227a\"\/>\n\n\n\n<div class=\"wp-block-jetpack-markdown\"><h2>Snippets<\/h2>\n<hr>\n<h3>1 | Dynamic Typing and Type Hinting<\/h3>\n<p>Python uses <strong>dynamic typing<\/strong>. What does this mean? Let\u2019s look at the following assignments:<\/p>\n<\/div>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">>>> my_var = 5\n>>> my_var = \"hello\"<\/pre>\n\n\n\n<div class=\"wp-block-jetpack-markdown\"><p>In the first line, the Python interpreter creates a label that points towards an integer. You didn\u2019t have to let your program know that <code>my_var<\/code> should be an integer. When the interpreter executed the first line, it looked at the object on the right-hand side of the equals sign. It determined that this is an integer based on the fact that it\u2019s a digit, without any quotation marks or brackets, and without a decimal point.<\/p>\n<p>On the second line, the Python interpreter has no problems switching the data type that the variable <code>my_var<\/code> stores. The interpreter determines the data type of a variable when the line of code runs, and it can change later on in the same program.<\/p>\n<p>This type of behaviour is not universal among programming languages. In statically-typed languages, the programmer needs to state what data type a variable will contain when the variable is first defined.<\/p>\n<p>As with most things, there are advantages and disadvantages for both systems that I won\u2019t get into. Dynamic typing certainly suits Python\u2019s style of programming very well.<\/p>\n<h4>Duck typing<\/h4>\n<p>You\u2019ll also hear the term duck typing used to refer to a related concept. The term comes from the phrase \u201cif it walks like a duck and it quacks like a duck, then it is a duck\u201d. This idea points to the fact that in many instances, what matters is not what the actual data type is, but what properties the object has.<\/p>\n<p>An example of this concept is indexing:<\/p>\n<\/div>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">>>> name = \"hello\"\n>>> numbers = [4, 5, 6, 5, 6]\n>>> more_numbers = 23, 34, 45, 56, 3\n>>> is_raining = True\n>>> name[3]\n'l'\n>>> numbers[3]\n5\n>>> more_numbers[3]\n56\n>>> is_raining[3]\nTraceback (most recent call last):\n  File \"&lt;input>\", line 1, in &lt;module>\nTypeError: 'bool' object is not subscriptable<\/pre>\n\n\n\n<div class=\"wp-block-jetpack-markdown\"><p>The same square brackets notation performs the same task on several data types. In the example above, lists, tuples and strings can all be indexed. Booleans cannot, though.<\/p>\n<h4>Type hinting<\/h4>\n<p>Python 3.5 introduced type hinting. Type hints do not change Python from a dynamically to a statically-typed language. Instead, as the name suggests, they serve only as hints. Have a look at the following example, which uses type hinting:<\/p>\n<\/div>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">>>> my_list: list = [4, 5, 6, 7]\n>>> my_list: list = \"hello\"\n>>> my_list\n'hello'<\/pre>\n\n\n\n<div class=\"wp-block-jetpack-markdown\"><p>You\u2019re adding a type hint when creating the variable <code>my_list<\/code>. However, in the second line you assign a string to this variable, and there are no complaints from Python\u2019s interpreter.<\/p>\n<p>You\u2019ve already seen an example of type hinting when used with parameters in function definitions and how tools such as IDEs make use of type hints to assist you with your coding.<\/p>\n<p>You may be working on projects as part of a team where type hinting is used as standard. Type hinting has been used more and more in recent years, especially in the context of production-level code.<\/p>\n<p>For most other applications, it\u2019s up to you on how and when to use type hinting. There are times when the extra information can make a significant contribution to making your code more readable. In other instances, you may use it to make the most of the IDEs functionality or other third-party tools that rely on type hinting for performing checks on your code.<\/p>\n<hr>\n<h3>2 | Dunder Methods<\/h3>\n<p>You\u2019ve already come across one of the dunder methods you\u2019ll see when you define a class in object-oriented programming. These methods whose names start and end with a double underscore have a special status, and they perform specific tasks.<\/p>\n<p>Let\u2019s look at a few more in this Snippet. You\u2019ll use the <code>Product<\/code> class you defined earlier in the Chapter:<\/p>\n<\/div>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\"># market_stall.py\n\nclass Product:\n    def __init__(self, name, cost_price, selling_price, number_in_stock):\n        self.name = name\n        self.cost_price = cost_price\n        self.selling_price = selling_price\n        self.number_in_stock = number_in_stock\n\n    def decrease_stock(self, quantity):\n        self.number_in_stock -= quantity\n\n    def change_cost_price(self, new_price):\n        self.cost_price = new_price\n\n    def change_selling_price(self, new_price):\n        self.selling_price = new_price\n\n    def show_stock(self):\n        print(f\"{self.name} | Number in stock: {self.number_in_stock}\")<\/pre>\n\n\n\n<div class=\"wp-block-jetpack-markdown\"><p>Let\u2019s experiment with this in a new script <code>testing_dunder_methods.py<\/code>:<\/p>\n<\/div>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\"># testing_dunder_methods.py\n\nfrom market_stall import Product\n\na_product = Product(\"Coffee\", 1.1, 2.5, 30)\n\nprint(a_product)<\/pre>\n\n\n\n<div class=\"wp-block-jetpack-markdown\"><p>The output from this shows the following:<\/p>\n<pre><code class=\"language-console\">&lt;market_stall.Product object at 0x7fec10a6e9d0&gt;\n<\/code><\/pre>\n<p>This output is not very useful in most instances.<\/p>\n<h4>The <code>__str__()<\/code> method<\/h4>\n<p>You may want to customise what happens when you print an object of type <code>Product<\/code>. To do this, you need to define a dunder method:<\/p>\n<\/div>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"22-23\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\"># market_stall.py\n\nclass Product:\n    def __init__(self, name, cost_price, selling_price, number_in_stock):\n        self.name = name\n        self.cost_price = cost_price\n        self.selling_price = selling_price\n        self.number_in_stock = number_in_stock\n\n    def decrease_stock(self, quantity):\n        self.number_in_stock -= quantity\n\n    def change_cost_price(self, new_price):\n        self.cost_price = new_price\n\n    def change_selling_price(self, new_price):\n        self.selling_price = new_price\n\n    def show_stock(self):\n        print(f\"{self.name} | Number in stock: {self.number_in_stock}\")\n\n    def __str__(self):\n        return f\"{self.name} | Selling Price: \u00a3{self.selling_price}\"<\/pre>\n\n\n\n<div class=\"wp-block-jetpack-markdown\"><p>The <code>__str__()<\/code> dunder method has the self parameter and returns a string. If you rerun <code>testing_dunder_methods.py<\/code> now you\u2019ll get a different output when you print the object:<\/p>\n<pre><code class=\"language-console\">Coffee | Selling Price: \u00a32.5\n<\/code><\/pre>\n<p>You can also format the price a bit further:<\/p>\n<\/div>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"23\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\"># market_stall.py\n\nclass Product:\n    def __init__(self, name, cost_price, selling_price, number_in_stock):\n        self.name = name\n        self.cost_price = cost_price\n        self.selling_price = selling_price\n        self.number_in_stock = number_in_stock\n\n    def decrease_stock(self, quantity):\n        self.number_in_stock -= quantity\n\n    def change_cost_price(self, new_price):\n        self.cost_price = new_price\n\n    def change_selling_price(self, new_price):\n        self.selling_price = new_price\n\n    def show_stock(self):\n        print(f\"{self.name} | Number in stock: {self.number_in_stock}\")\n\n    def __str__(self):\n        return f\"{self.name} | Selling Price: \u00a3{self.selling_price:.2f}\"<\/pre>\n\n\n\n<div class=\"wp-block-jetpack-markdown\"><p>Following the <code>selling_price<\/code> instance variable in the curly brackets of the f-string, you\u2019ve added a colon to format the output further. The code following the colon formats the float and displays it with two decimal places:<\/p>\n<pre><code class=\"language-console\">Coffee | Selling Price: \u00a32.50\n<\/code><\/pre>\n<p>It\u2019s up to you as the programmer to decide how you\u2019d like the object to be displayed when you need to print it out.<\/p>\n<h4>Comparison operators<\/h4>\n<p>Let\u2019s try the following operation on two objects of type <code>Product<\/code>:<\/p>\n<\/div>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"6,8\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\"># testing_dunder_methods.py\n\nfrom market_stall import Product\n\na_product = Product(\"Coffee\", 1.1, 2.5, 30)\nanother_product = Product(\"Chocolate\",  0.9, 1.75, 35)\n\nprint(a_product > another_product)<\/pre>\n\n\n\n<div class=\"wp-block-jetpack-markdown\"><p>You\u2019re using one of the comparison operators to check whether one object is greater than the other. But what does this mean in the context of objects of type <code>Product<\/code>? Let\u2019s see whether the Python interpreter can figure this out:<\/p>\n<pre><code class=\"language-console\">Traceback (most recent call last):\n  File &quot;&lt;path&gt;\/testing_dunder_methods.py&quot;, line 8, in &lt;module&gt;\n    print(a_product &gt; another_product)\nTypeError: '&gt;' not supported between instances of 'Product' and 'Product'\n<\/code><\/pre>\n<p>No, it cannot. You can see the <code>TypeError<\/code> stating that the <code>&gt;<\/code> operator is not supported between two objects of type <code>Product<\/code>. However, you can fix this with the <code>__gt__()<\/code> dunder method, which defines the behaviour for the <strong>g<\/strong>reater <strong>t<\/strong>han operator:<\/p>\n<\/div>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"25-26\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\"># market_stall.py\n\nclass Product:\n    def __init__(self, name, cost_price, selling_price, number_in_stock):\n        self.name = name\n        self.cost_price = cost_price\n        self.selling_price = selling_price\n        self.number_in_stock = number_in_stock\n\n    def decrease_stock(self, quantity):\n        self.number_in_stock -= quantity\n\n    def change_cost_price(self, new_price):\n        self.cost_price = new_price\n\n    def change_selling_price(self, new_price):\n        self.selling_price = new_price\n\n    def show_stock(self):\n        print(f\"{self.name} | Number in stock: {self.number_in_stock}\")\n\n    def __str__(self):\n        return f\"{self.name} | Selling Price: \u00a3{self.selling_price:.2f}\"\n\n    def __gt__(self, other):\n        return self.selling_price > other.selling_price<\/pre>\n\n\n\n<div class=\"wp-block-jetpack-markdown\"><p>The <code>__gt__()<\/code> dunder method has two parameters. You\u2019ll see that the IDE autofills both of these. Since this operator compares two objects, there\u2019s <code>self<\/code> and <code>other<\/code> to represent the two objects. The <code>self<\/code> parameter represents the object to the left of the <code>&gt;<\/code> sign, and <code>other<\/code> represents the object on the right.<\/p>\n<p>In this case, we\u2019re assuming that in the context of objects of type <code>Product<\/code>, the result of the <code>&gt;<\/code> operator should be determined based on the selling price of both products. The <code>return<\/code> statement in this dunder method should return a Boolean data type.<\/p>\n<p>Here are some other related operators you can also define:<\/p>\n<ul>\n<li>less than operator <code>&lt;<\/code> using <code>__lt__()<\/code><\/li>\n<li>less than or equal operator <code>&lt;<\/code>= using <code>__le__()<\/code><\/li>\n<li>greater than or equal operator <code>&gt;=<\/code> using <code>__ge__()<\/code><\/li>\n<li>equality operator <code>==<\/code> using <code>__eq__()<\/code><\/li>\n<\/ul>\n<h4>Arithmetic operators<\/h4>\n<p>Let\u2019s finish with one last dunder method. What happens if you try to add two objects of type <code>Product<\/code> together:<\/p>\n<\/div>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"8\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\"># testing_dunder_methods.py\n\nfrom market_stall import Product\n\na_product = Product(\"Coffee\", 1.1, 2.5, 30)\nanother_product = Product(\"Chocolate\",  0.9, 1.75, 35)\n\nprint(a_product + another_product)<\/pre>\n\n\n\n<div class=\"wp-block-jetpack-markdown\"><p>You may have guessed it\u2019s not obvious what adding two products means. The program raises another <code>TypeError<\/code>:<\/p>\n<pre><code class=\"language-console\">Traceback (most recent call last):\n  File &quot;&lt;path&gt;\/testing_dunder_methods.py&quot;, line 8, in &lt;module&gt;\n    print(a_product + another_product)\nTypeError: unsupported operand type(s) for +: 'Product' and 'Product'\n<\/code><\/pre>\n<p>Another dunder method comes to the rescue. The <code>__add__()<\/code> dunder method defines how the <code>+<\/code> operator works for these objects:<\/p>\n<\/div>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"28-29\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\"># market_stall.py\n\nclass Product:\n    def __init__(self, name, cost_price, selling_price, number_in_stock):\n        self.name = name\n        self.cost_price = cost_price\n        self.selling_price = selling_price\n        self.number_in_stock = number_in_stock\n\n    def decrease_stock(self, quantity):\n        self.number_in_stock -= quantity\n\n    def change_cost_price(self, new_price):\n        self.cost_price = new_price\n\n    def change_selling_price(self, new_price):\n        self.selling_price = new_price\n\n    def show_stock(self):\n        print(f\"{self.name} | Number in stock: {self.number_in_stock}\")\n\n    def __str__(self):\n        return f\"{self.name} | Selling Price: \u00a3{self.selling_price:.2f}\"\n\n    def __gt__(self, other):\n        return self.selling_price > other.selling_price\n\n    def __add__(self, other):\n        return self.selling_price + other.selling_price<\/pre>\n\n\n\n<div class=\"wp-block-jetpack-markdown\"><p>Again, we\u2019ve decided that the total selling price is what we\u2019d like in this case. How you define these behaviours will depend on the class you\u2019re defining and how you want objects of this class to behave. You can try out <code>__sub__()<\/code> and <code>__mul__()<\/code> too!<\/p>\n<p>There are many other dunder methods that allow you to customise your class and how it behaves. For example, there is a dunder method to make a data type an iterable and another to make it indexable.<\/p>\n<hr>\n<h3>3 | Inheritance<\/h3>\n<p>In this Snippet you\u2019ll look at a brief introduction to the concept of inheritance in object-oriented programming. When you define a class, you\u2019re defining a template to create objects that have similar properties.<\/p>\n<p>You may need objects of groups which are similar to each other but different enough that they cannot use exactly the same class.<\/p>\n<p>Consider the market seller you met earlier in the Chapter. After using his code for a while, he noticed he has a problem. His code treats all sandwiches in the same way. However, he sells different types of sandwiches, and he wants to keep track of them separately.<\/p>\n<p>He decides to write a new class called <code>Sandwich<\/code>. However, this class has a lot in common with <code>Product<\/code>. Therefore, he wants the new class to inherit its properties from the <code>Product<\/code> class. He\u2019ll then make some additional changes.<\/p>\n<p><strong>Inheritance<\/strong> is a key area of object-oriented programming. To create a class that inherits from another class, you can add the parent class in the parentheses when you create the class:<\/p>\n<\/div>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">class Sandwich(Product):<\/pre>\n\n\n\n<div class=\"wp-block-jetpack-markdown\"><p>The <strong>child class<\/strong> <code>Sandwich<\/code> inherits from the <strong>parent class<\/strong> <code>Product<\/code>. The child class still needs an <code>__init__()<\/code> method:<\/p>\n<\/div>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\"># market_stall.py\n\n# Definition of Product not shown\n# ...\n\nclass Sandwich(Product):\n    def __init__(self, filling, cost_price, selling_price, number_in_stock):\n        super().__init__(\"Sandwich\", cost_price, selling_price, number_in_stock)\n        self.filling = filling<\/pre>\n\n\n\n<div class=\"wp-block-jetpack-markdown\"><p>The <code>__init__()<\/code> method parameters are similar to those of the parent class. There is one difference. The second parameter represents the filling of the sandwich and not the name of the product. The name of the product must be <code>&quot;Sandwich&quot;<\/code> for all objects of this type.<\/p>\n<h4>The <code>super()<\/code> function<\/h4>\n<p>The first line of the <code>__init__()<\/code> method has a new function you\u2019ve not seen so far. This is the <code>super()<\/code> function. This function allows you to access the properties of the parent class. You\u2019re calling the <code>__init__()<\/code> method of the parent class in the first line of <code>Sandwich<\/code>\u2019s <code>__init__()<\/code> method. This means that when you initialise an object of type <code>Sandwich<\/code>, you first initialise the parent class and then go on with specific tasks for the child class.<\/p>\n<p>The call to <code>super().__init__()<\/code> doesn\u2019t use the <code>filling<\/code> parameter an object of type <code>Product<\/code> does not need this. The first argument in <code>super().__init__()<\/code> is the string <code>&quot;Sandwich&quot;<\/code>, and this will be assigned to the instance variable <code>name<\/code>.<\/p>\n<p>The last line then creates a new instance variable <code>filling<\/code> which is specific only to this child class.<\/p>\n<p>Let\u2019s try this out in a new script called <code>testing_inheritance.py<\/code>:<\/p>\n<\/div>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\"># testing_inheritance.py\n\nfrom market_stall import Sandwich\n\ntype_1 = Sandwich(\"Cheese\", 1.7, 3.5, 10)\ntype_2 = Sandwich(\"Ham\", 1.9, 4, 10)\ntype_3 = Sandwich(\"Tuna\", 1.8, 4, 10)\n\nprint(type_1.name)\nprint(type_2.name)\nprint(type_3.name)\n\nprint(type_1.filling)\nprint(type_2.filling)\nprint(type_3.filling)<\/pre>\n\n\n\n<div class=\"wp-block-jetpack-markdown\"><p>You\u2019re creating three instances of the class <code>Sandwich<\/code> with different arguments. An object of type <code>Sandwich<\/code> has all the properties of an object of type <code>Product<\/code>. You can see for the first three lines printed out that all objects have the same value for the instance variable <code>name<\/code>:<\/p>\n<pre><code class=\"language-console\">Sandwich\nSandwich\nSandwich\nCheese\nHam\nTuna\n<\/code><\/pre>\n<p>However, they all have different values for <code>filling<\/code>. Let\u2019s see what happens when you print the object directly:<\/p>\n<\/div>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"9-11\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\"># testing_inheritance.py\n\nfrom market_stall import Sandwich\n\ntype_1 = Sandwich(\"Cheese\", 1.7, 3.5, 10)\ntype_2 = Sandwich(\"Ham\", 1.9, 4, 10)\ntype_3 = Sandwich(\"Tuna\", 1.8, 4, 10)\n\nprint(type_1)\nprint(type_2)\nprint(type_3)<\/pre>\n\n\n\n<div class=\"wp-block-jetpack-markdown\"><p>This gives the output defined by the <code>__str__()<\/code> dunder method of the parent class <code>Product<\/code>:<\/p>\n<pre><code class=\"language-console\">Sandwich | Selling Price: \u00a33.50\nSandwich | Selling Price: \u00a34.00\nSandwich | Selling Price: \u00a34.00\n<\/code><\/pre>\n<h4>Overriding methods<\/h4>\n<p>However, you can define a <code>__str__()<\/code> dunder method specifically for the <code>Sandwich<\/code> class:<\/p>\n<\/div>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"11-12\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\"># market_stall.py\n\n# Definition of Product not shown\n# ...\n\nclass Sandwich(Product):\n    def __init__(self, filling, cost_price, selling_price, number_in_stock):\n        super().__init__(\"Sandwich\", cost_price, selling_price, number_in_stock)\n        self.filling = filling\n\n    def __str__(self):\n        return f\"{self.filling} sandwich | Selling Price: \u00a3{self.selling_price:.2f}\"<\/pre>\n\n\n\n<div class=\"wp-block-jetpack-markdown\"><p><code>Sandwich<\/code>\u2019s <code>__str__()<\/code> method <strong>overrides<\/strong> the same method in the parent class <code>Product<\/code>. The output from <code>testing_inheritance.py<\/code> now looks as follows:<\/p>\n<pre><code class=\"language-console\">Cheese sandwich | Selling Price: \u00a33.50\nHam sandwich | Selling Price: \u00a34.00\nTuna sandwich | Selling Price: \u00a34.00\n<\/code><\/pre>\n<p>You should also override the <code>show_stock()<\/code> method similarly.<\/p>\n<p>In the same way that you\u2019ve added a data attribute to the child class, in this case <code>filling<\/code>, which doesn\u2019t exist for the parent class, you can also create methods specifically for the child class.<\/p>\n<\/div>\n\n\n\n<div style=\"height:30px\" aria-hidden=\"true\" class=\"wp-block-spacer\"><\/div>\n\n\n\n<hr class=\"wp-block-separator has-text-color has-alpha-channel-opacity has-background aligncenter is-style-wide\" style=\"background-color:#6d227a;color:#6d227a\"\/>\n\n\n\n<div class=\"wp-block-buttons is-horizontal is-content-justification-center is-layout-flex wp-container-core-buttons-is-layout-7d812b4c wp-block-buttons-is-layout-flex\">\n<div class=\"wp-block-button has-custom-width wp-block-button__width-50 is-style-outline is-style-outline--2\"><a class=\"wp-block-button__link has-text-color wp-element-button\" href=\"https:\/\/thepythoncodingbook.com\/using-numpy-numerical-python-for-quantitative-applications\/\" style=\"border-radius:3px;color:#6d227a\">Next Chapter<\/a><\/div>\n<\/div>\n\n\n\n<div style=\"height:30px\" aria-hidden=\"true\" class=\"wp-block-spacer\"><\/div>\n\n\n\n<div class=\"wp-block-buttons is-horizontal is-content-justification-center is-layout-flex wp-container-core-buttons-is-layout-7d812b4c wp-block-buttons-is-layout-flex\">\n<div class=\"wp-block-button has-custom-width wp-block-button__width-75 is-style-fill\"><a class=\"wp-block-button__link has-text-color has-background wp-element-button\" href=\"https:\/\/thepythoncodingbook.com\/book-outline\/\" style=\"border-radius:3px;color:#0d363a;background-color:#fdb33b\">Browse Zeroth Edition<\/a><\/div>\n<\/div>\n\n\n\n<div style=\"height:30px\" aria-hidden=\"true\" class=\"wp-block-spacer\"><\/div>\n\n\n\n<p class=\"wp-block-paragraph\"><\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><\/h2>\n\n\n\n<h4 class=\"wp-block-heading\"><\/h4>\n\n\n\n<div class=\"wp-block-jetpack-markdown\"><\/div>\n\n\n\n\n\n<hr class=\"wp-block-separator has-text-color has-alpha-channel-opacity has-background aligncenter is-style-wide\" style=\"background-color:#6d227a;color:#6d227a\"\/>\n\n\n\n<div class=\"wp-block-group\"><div class=\"wp-block-group__inner-container is-layout-constrained wp-block-group-is-layout-constrained\">\n<div class=\"wp-block-group alignfull\"><div class=\"wp-block-group__inner-container is-layout-constrained wp-block-group-is-layout-constrained\">\n<div class=\"wp-block-group alignfull\"><div class=\"wp-block-group__inner-container is-layout-constrained wp-block-group-is-layout-constrained\">\n<div class=\"wp-block-coblocks-hero alignfull coblocks-hero-230194844519\"><div class=\"wp-block-coblocks-hero__inner has-background hero-center-left-align has-padding has-huge-padding\" style=\"background-color:#1a6b72;min-height:500px\"><div class=\"wp-block-coblocks-hero__content-wrapper\"><div class=\"wp-block-coblocks-hero__content\" style=\"max-width:560px\">\n<h2 class=\"wp-block-heading has-text-color has-link-color wp-elements-806dd89de56256fb948e5020de497de4\" style=\"color:#fff3e6\">Become a Member of<\/h2>\n\n\n\n<h2 class=\"wp-block-heading has-text-color has-link-color wp-elements-7d78fcf199c064aa3173690e46837383\" style=\"color:#fff3e6\">The Python Coding Place<\/h2>\n\n\n\n<p class=\"has-text-color has-link-color wp-elements-57091ca0dd26b2b579f184ab1723dc89 wp-block-paragraph\" style=\"color:#fff3e6\">Video courses, live cohort-based courses, workshops, weekly videos, members&#8217; forum, and more\u2026<\/p>\n\n\n\n<div style=\"height:66px\" aria-hidden=\"true\" class=\"wp-block-spacer\"><\/div>\n\n\n\n<div class=\"wp-block-buttons is-layout-flex wp-block-buttons-is-layout-flex\">\n<div class=\"wp-block-button has-custom-width wp-block-button__width-50\"><a class=\"wp-block-button__link has-black-color has-text-color has-background wp-element-button\" href=\"https:\/\/thepythoncodingplace.com\" style=\"background-color:#fdb33b\">Become a Member<\/a><\/div>\n<\/div>\n<\/div><\/div><\/div><\/div>\n<\/div><\/div>\n<\/div><\/div>\n<\/div><\/div>\n\n\n\n\n","protected":false},"excerpt":{"rendered":"","protected":false},"author":192321682,"featured_media":0,"parent":0,"menu_order":0,"comment_status":"closed","ping_status":"closed","template":"templates\/full-width-page.php","meta":{"_coblocks_attr":"","_coblocks_dimensions":"","_coblocks_responsive_height":"","_coblocks_accordion_ie_support":"","_crdt_document":"","footnotes":""},"class_list":["post-988","page","type-page","status-publish","hentry"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.4 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>7 | Object-Oriented Programming - The Python Coding Book<\/title>\n<meta name=\"description\" content=\"This Chapter introduces object-oriented programming. The concepts and the terminology of classes, objects, attributes, and more are explained\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/thepythoncodingbook.com\/object-oriented-programming\/\" \/>\n<meta property=\"og:locale\" content=\"en_GB\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"7 | Object-Oriented Programming - The Python Coding Book\" \/>\n<meta property=\"og:description\" content=\"This Chapter introduces object-oriented programming. The concepts and the terminology of classes, objects, attributes, and more are explained\" \/>\n<meta property=\"og:url\" content=\"https:\/\/thepythoncodingbook.com\/object-oriented-programming\/\" \/>\n<meta property=\"og:site_name\" content=\"The Python Coding Book\" \/>\n<meta property=\"article:modified_time\" content=\"2023-11-12T12:51:11+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/thepythoncodingbook.com\/wp-content\/uploads\/2021\/07\/ch7_split_screen-1024x296.png\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Estimated reading time\" \/>\n\t<meta name=\"twitter:data1\" content=\"33 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\\\/\\\/schema.org\",\"@graph\":[{\"@type\":\"WebPage\",\"@id\":\"https:\\\/\\\/thepythoncodingbook.com\\\/object-oriented-programming\\\/\",\"url\":\"https:\\\/\\\/thepythoncodingbook.com\\\/object-oriented-programming\\\/\",\"name\":\"7 | Object-Oriented Programming - The Python Coding Book\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/thepythoncodingbook.com\\\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\\\/\\\/thepythoncodingbook.com\\\/object-oriented-programming\\\/#primaryimage\"},\"image\":{\"@id\":\"https:\\\/\\\/thepythoncodingbook.com\\\/object-oriented-programming\\\/#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/thepythoncodingbook.com\\\/wp-content\\\/uploads\\\/2021\\\/07\\\/ch7_split_screen-1024x296.png\",\"datePublished\":\"2021-07-30T09:13:14+00:00\",\"dateModified\":\"2023-11-12T12:51:11+00:00\",\"description\":\"This Chapter introduces object-oriented programming. The concepts and the terminology of classes, objects, attributes, and more are explained\",\"breadcrumb\":{\"@id\":\"https:\\\/\\\/thepythoncodingbook.com\\\/object-oriented-programming\\\/#breadcrumb\"},\"inLanguage\":\"en-GB\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/thepythoncodingbook.com\\\/object-oriented-programming\\\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-GB\",\"@id\":\"https:\\\/\\\/thepythoncodingbook.com\\\/object-oriented-programming\\\/#primaryimage\",\"url\":\"https:\\\/\\\/i0.wp.com\\\/thepythoncodingbook.com\\\/wp-content\\\/uploads\\\/2021\\\/07\\\/ch7_split_screen.png?fit=2798%2C808&ssl=1\",\"contentUrl\":\"https:\\\/\\\/i0.wp.com\\\/thepythoncodingbook.com\\\/wp-content\\\/uploads\\\/2021\\\/07\\\/ch7_split_screen.png?fit=2798%2C808&ssl=1\",\"width\":2798,\"height\":808},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/thepythoncodingbook.com\\\/object-oriented-programming\\\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\\\/\\\/thepythoncodingbook.com\\\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"7 | Object-Oriented Programming\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\\\/\\\/thepythoncodingbook.com\\\/#website\",\"url\":\"https:\\\/\\\/thepythoncodingbook.com\\\/\",\"name\":\"The Python Coding Book\",\"description\":\"The friendly, relaxed programming book\",\"publisher\":{\"@id\":\"https:\\\/\\\/thepythoncodingbook.com\\\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\\\/\\\/thepythoncodingbook.com\\\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-GB\"},{\"@type\":\"Organization\",\"@id\":\"https:\\\/\\\/thepythoncodingbook.com\\\/#organization\",\"name\":\"Codetoday\",\"url\":\"https:\\\/\\\/thepythoncodingbook.com\\\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-GB\",\"@id\":\"https:\\\/\\\/thepythoncodingbook.com\\\/#\\\/schema\\\/logo\\\/image\\\/\",\"url\":\"https:\\\/\\\/i0.wp.com\\\/thepythoncodingbook.com\\\/wp-content\\\/uploads\\\/2021\\\/04\\\/cropped-icon-only.png?fit=512%2C512&ssl=1\",\"contentUrl\":\"https:\\\/\\\/i0.wp.com\\\/thepythoncodingbook.com\\\/wp-content\\\/uploads\\\/2021\\\/04\\\/cropped-icon-only.png?fit=512%2C512&ssl=1\",\"width\":512,\"height\":512,\"caption\":\"Codetoday\"},\"image\":{\"@id\":\"https:\\\/\\\/thepythoncodingbook.com\\\/#\\\/schema\\\/logo\\\/image\\\/\"}}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"7 | Object-Oriented Programming - The Python Coding Book","description":"This Chapter introduces object-oriented programming. The concepts and the terminology of classes, objects, attributes, and more are explained","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/thepythoncodingbook.com\/object-oriented-programming\/","og_locale":"en_GB","og_type":"article","og_title":"7 | Object-Oriented Programming - The Python Coding Book","og_description":"This Chapter introduces object-oriented programming. The concepts and the terminology of classes, objects, attributes, and more are explained","og_url":"https:\/\/thepythoncodingbook.com\/object-oriented-programming\/","og_site_name":"The Python Coding Book","article_modified_time":"2023-11-12T12:51:11+00:00","og_image":[{"url":"https:\/\/thepythoncodingbook.com\/wp-content\/uploads\/2021\/07\/ch7_split_screen-1024x296.png","type":"","width":"","height":""}],"twitter_card":"summary_large_image","twitter_misc":{"Estimated reading time":"33 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"WebPage","@id":"https:\/\/thepythoncodingbook.com\/object-oriented-programming\/","url":"https:\/\/thepythoncodingbook.com\/object-oriented-programming\/","name":"7 | Object-Oriented Programming - The Python Coding Book","isPartOf":{"@id":"https:\/\/thepythoncodingbook.com\/#website"},"primaryImageOfPage":{"@id":"https:\/\/thepythoncodingbook.com\/object-oriented-programming\/#primaryimage"},"image":{"@id":"https:\/\/thepythoncodingbook.com\/object-oriented-programming\/#primaryimage"},"thumbnailUrl":"https:\/\/thepythoncodingbook.com\/wp-content\/uploads\/2021\/07\/ch7_split_screen-1024x296.png","datePublished":"2021-07-30T09:13:14+00:00","dateModified":"2023-11-12T12:51:11+00:00","description":"This Chapter introduces object-oriented programming. The concepts and the terminology of classes, objects, attributes, and more are explained","breadcrumb":{"@id":"https:\/\/thepythoncodingbook.com\/object-oriented-programming\/#breadcrumb"},"inLanguage":"en-GB","potentialAction":[{"@type":"ReadAction","target":["https:\/\/thepythoncodingbook.com\/object-oriented-programming\/"]}]},{"@type":"ImageObject","inLanguage":"en-GB","@id":"https:\/\/thepythoncodingbook.com\/object-oriented-programming\/#primaryimage","url":"https:\/\/i0.wp.com\/thepythoncodingbook.com\/wp-content\/uploads\/2021\/07\/ch7_split_screen.png?fit=2798%2C808&ssl=1","contentUrl":"https:\/\/i0.wp.com\/thepythoncodingbook.com\/wp-content\/uploads\/2021\/07\/ch7_split_screen.png?fit=2798%2C808&ssl=1","width":2798,"height":808},{"@type":"BreadcrumbList","@id":"https:\/\/thepythoncodingbook.com\/object-oriented-programming\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/thepythoncodingbook.com\/"},{"@type":"ListItem","position":2,"name":"7 | Object-Oriented Programming"}]},{"@type":"WebSite","@id":"https:\/\/thepythoncodingbook.com\/#website","url":"https:\/\/thepythoncodingbook.com\/","name":"The Python Coding Book","description":"The friendly, relaxed programming book","publisher":{"@id":"https:\/\/thepythoncodingbook.com\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/thepythoncodingbook.com\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-GB"},{"@type":"Organization","@id":"https:\/\/thepythoncodingbook.com\/#organization","name":"Codetoday","url":"https:\/\/thepythoncodingbook.com\/","logo":{"@type":"ImageObject","inLanguage":"en-GB","@id":"https:\/\/thepythoncodingbook.com\/#\/schema\/logo\/image\/","url":"https:\/\/i0.wp.com\/thepythoncodingbook.com\/wp-content\/uploads\/2021\/04\/cropped-icon-only.png?fit=512%2C512&ssl=1","contentUrl":"https:\/\/i0.wp.com\/thepythoncodingbook.com\/wp-content\/uploads\/2021\/04\/cropped-icon-only.png?fit=512%2C512&ssl=1","width":512,"height":512,"caption":"Codetoday"},"image":{"@id":"https:\/\/thepythoncodingbook.com\/#\/schema\/logo\/image\/"}}]}},"jetpack_likes_enabled":true,"jetpack_sharing_enabled":true,"jetpack_shortlink":"https:\/\/wp.me\/Pd1Q8F-fW","_links":{"self":[{"href":"https:\/\/thepythoncodingbook.com\/wp-json\/wp\/v2\/pages\/988","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/thepythoncodingbook.com\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/thepythoncodingbook.com\/wp-json\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/thepythoncodingbook.com\/wp-json\/wp\/v2\/users\/192321682"}],"replies":[{"embeddable":true,"href":"https:\/\/thepythoncodingbook.com\/wp-json\/wp\/v2\/comments?post=988"}],"version-history":[{"count":66,"href":"https:\/\/thepythoncodingbook.com\/wp-json\/wp\/v2\/pages\/988\/revisions"}],"predecessor-version":[{"id":3345,"href":"https:\/\/thepythoncodingbook.com\/wp-json\/wp\/v2\/pages\/988\/revisions\/3345"}],"wp:attachment":[{"href":"https:\/\/thepythoncodingbook.com\/wp-json\/wp\/v2\/media?parent=988"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}