{"id":115887,"date":"2020-07-25T21:29:00","date_gmt":"2020-07-25T21:29:00","guid":{"rendered":"https:\/\/blog.finxter.com\/?p=5133"},"modified":"2020-07-25T21:29:00","modified_gmt":"2020-07-25T21:29:00","slug":"what-is-__init__-in-python","status":"publish","type":"post","link":"https:\/\/sickgaming.net\/blog\/2020\/07\/25\/what-is-__init__-in-python\/","title":{"rendered":"What is __init__ in Python?"},"content":{"rendered":"<p>When reading over other people&#8217;s Python code, many beginners are puzzled by the <code>__init__(self)<\/code> method. What\u2019s its purpose? This article answers this question once and for all.<\/p>\n<figure class=\"wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio\">\n<div class=\"wp-block-embed__wrapper\">\n<div class=\"ast-oembed-container\"><iframe loading=\"lazy\" title=\"What is __init__ in Python?\" width=\"1400\" height=\"788\" src=\"https:\/\/www.youtube.com\/embed\/HgquEfCW1SQ?feature=oembed\" frameborder=\"0\" allow=\"accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture\" allowfullscreen><\/iframe><\/div>\n<\/div>\n<\/figure>\n<p><strong>What&#8217;s the purpose of <code>__init__(self)<\/code> in Python? <\/strong><\/p>\n<p class=\"has-pale-cyan-blue-background-color has-background\">The reserved Python method <code>__init__()<\/code> is called the <em>constructor <\/em>of a class. You can call the constructor method to create an object (=instance) from a class and initialize its attributes.<\/p>\n<figure class=\"wp-block-image size-large\"><img decoding=\"async\" src=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/07\/pythonint-1024x576.jpg\" alt=\"Python __init__ method constructor\" class=\"wp-image-11424\" srcset=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/07\/pythonint-scaled.jpg 1024w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/07\/pythonint-300x169.jpg 300w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/07\/pythonint-768x432.jpg 768w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/07\/pythonint-150x84.jpg 150w\" sizes=\"(max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n<p>While this answers the question, if you&#8217;ve got any ambition in becoming a professional Python coder, it&#8217;s not enough to know that the <code>__init__<\/code> method is the constructor of a class. You also need to know how to use the constructor in your own projects&#8212;and how to customize its arguments. A thorough understanding of the constructor serves as a strong foundation for more advanced concepts in object-oriented Python programming. Read on to learn the other half of the equation.<\/p>\n<p><strong>Interactive Example<\/strong>: Before I&#8217;ll explain it to you, let&#8217;s open your knowledge gap. Consider the following example:<\/p>\n<p> <iframe loading=\"lazy\" src=\"https:\/\/trinket.io\/embed\/python\/fbc1b43146\" marginwidth=\"0\" marginheight=\"0\" allowfullscreen=\"\" width=\"100%\" height=\"356\" frameborder=\"0\"><\/iframe> <\/p>\n<p><em><strong>Exercise<\/strong>: Add one argument color to the <code>__init__<\/code> method and make the code run without error!<\/em><\/p>\n<p>Let&#8217;s dive into this simple example in great detail.<\/p>\n<h2>How to Use the __init__ Method in Practice? A Simple Example<\/h2>\n<p>We&#8217;ll use some terms of object-oriented programming in Python to explain our example. Make sure to study the following cheat sheet (you can also <a href=\"https:\/\/blog.finxter.com\/python-cheat-sheets\/\">download the PDF here<\/a>). Click the image to get the cheat sheet (opens in a new tab). If you&#8217;re already comfortable with basic object-orientation terminologies like classes and instances, simply read on.<\/p>\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter is-resized\"><a href=\"https:\/\/blog.finxter.com\/object-oriented-programming-terminology-cheat-sheet\/\" target=\"_blank\" rel=\"noreferrer noopener\"><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2019\/03\/CheatSheet-Python-8_-OO-Terminology-1-791x1024.jpg\" alt=\"\" class=\"wp-image-2163\" width=\"198\" height=\"256\" srcset=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2019\/03\/CheatSheet-Python-8_-OO-Terminology-1.jpg 791w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2019\/03\/CheatSheet-Python-8_-OO-Terminology-1-232x300.jpg 232w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2019\/03\/CheatSheet-Python-8_-OO-Terminology-1-768x994.jpg 768w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2019\/03\/CheatSheet-Python-8_-OO-Terminology-1-100x129.jpg 100w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2019\/03\/CheatSheet-Python-8_-OO-Terminology-1-864x1118.jpg 864w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2019\/03\/CheatSheet-Python-8_-OO-Terminology-1-1200x1553.jpg 1200w\" sizes=\"auto, (max-width: 198px) 100vw, 198px\" \/><\/a><\/figure>\n<\/div>\n<p>You&#8217;ve learned that the <code>__init__<\/code> method is the constructor method of a class. You call the constructor method to create new instances (or <em>objects<\/em>). But how exactly does this play out in practice? Before we dive into the correct use, we need to understand the <em>arguments <\/em>(or <em>parameters<\/em>) of the constructor method.<\/p>\n<h3>The Self Argument<\/h3>\n<p>The <code>__init__<\/code> constructor requires at least one argument. According to the <a href=\"https:\/\/www.python.org\/dev\/peps\/pep-0570\/\">PEP8 standard<\/a>, it&#8217;s good practice to denote this argument as <code>self<\/code>. In any case, the <code>self<\/code> argument points to the newly-created instance itself and it allows you to manipulate the instance attributes of the new instance. In the dog example, you&#8217;d use <code>self.color = \"blue\"<\/code> to set the newly-created dog&#8217;s <code>color<\/code> attribute to the string <code>\"blue\"<\/code>. <\/p>\n<p>Let&#8217;s have a look at the following basic code example:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">class Dog: def __init__(self): self.color = \"blue\" bello = Dog()\nprint(bello.color)\n# blue<\/pre>\n<ol>\n<li>We create a new class Dog with the constructor <code>__init__(self)<\/code>. <\/li>\n<li>We create a new instance of the class <code>Dog<\/code> named <code>bello<\/code>. There are two interesting observations: First, we use the class name rather than the constructor name to create the new instance. Python internally calls the __init__ method for us. Second, we don&#8217;t pass any argument when calling <code>Dog()<\/code>. Again, Python implicitly passes a reference to the newly created instance (<code>bello<\/code>) to the constructor <code>__init__<\/code>. <\/li>\n<li>We print the color attribute of the newly-created <code>bello<\/code> instance. The result is the string value <code>\"blue\"<\/code> as defined in the constructor.<\/li>\n<\/ol>\n<p>However, this minimal example is unrealistic. Some dogs are brown, others are black, and only some are blue.<\/p>\n<h3>Multiple Constructor Arguments<\/h3>\n<p>So how can we create different dogs with different colors? We can easily achieve this by using more arguments, in addition to <code>self<\/code>, when defining our constructor <code>__init__<\/code>. Here&#8217;s another example where we create two dogs with different colors. Can you spot their colors?<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">class Dog: def __init__(self, color): self.color = color bello = Dog(\"blue\")\nprint(bello.color)\n# blue alice = Dog(\"brown\")\nprint(alice.color)\n# brown<\/pre>\n<p>In contrast to the first example, we now define the constructor <code>__init__(self, color)<\/code> with two arguments rather than one. <\/p>\n<p>The first is the <code>self<\/code> argument as before. The second is a custom argument <code>color<\/code> that is passed through by the caller of the constructor. In our case, we create two Dog instances, <code>bello<\/code> and <code>alice<\/code>, by specifying the <code>color<\/code> argument for both. <\/p>\n<p>Note that the <code>self<\/code> argument is handled implicitly by the Python programming environment: Python simply passes a reference to the respective <code>Dog<\/code> instance to the <code>__init__<\/code> constructor.<\/p>\n<h2>What&#8217;s the Difference between the Constructor and the Initializer?<\/h2>\n<p>Well, I haven&#8217;t used a very accurate terminology in the previous paragraphs. I used the term &#8220;constructor&#8221; for both the call <code>Dog()<\/code> and the call <code>__init__()<\/code>. But only the former call can be denoted as <em>constructor method<\/em> because only this call actually creates a new instance. At the time, we call the method <code>__init__<\/code>, the instance has already been created (Python passes it to us via the <code>self<\/code> argument). That&#8217;s why a more precise term for the <code>__init__<\/code> method is <strong><em>initializer method<\/em><\/strong>. That&#8217;s how I&#8217;ll denote it in the following to make up for it. <img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/12.0.0-1\/72x72\/1f609.png\" alt=\"\ud83d\ude09\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/><\/p>\n<h2>What&#8217;s the Meaning of the Underscores in the __init__ Method Name?<\/h2>\n<p>I&#8217;ve written a whole article about the <a href=\"https:\/\/blog.finxter.com\/underscore-in-python\/\">meaning of the underscore in Python<\/a>. Check it out if this topic interests you further. The key takeaway, however, is the following:<\/p>\n<p>The double underscore \u201c__\u201d (called <em>\u201cdunder\u201c<\/em>) is used to make an instance attribute or method private (cannot be accessed from outside the class) \u2014 when used as leading dunder. When used as enclosing dunder (e.g. \u201c__init__\u201d) it indicates that it is a special method in Python (called \u201cmagic method\u201d).<\/p>\n<h2>How to Use __init__ in an Inherited Class?<\/h2>\n<p>An inherited class is a class that inherits all attributes and methods from a parent class. Here&#8217;s an example:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">class Dog: def __init__(self, color): self.color = color class CuteDog(Dog): def __init__(self, color): Dog.__init__(self, color) self.hairs = True bello = CuteDog('brown')\nprint(bello.hairs)\n# True print(bello.color)\n# brown<\/pre>\n<p>Inheritance is very important in Python. In the example, the parent class is the class Dog you already know from above. The initializer method __init__ defines the color of this dog.<\/p>\n<p>Now, we also create a new class <code>CuteDog<\/code> that inherits all attributes from the parent class <code>Dog<\/code>. You can define inheritance by specifying the name of the parent class within the brackets after the child class: <code>CuteDog(Dog)<\/code>.<\/p>\n<p>The interesting thing is that the __init__ method of the child class CuteDog calls the __init__ method of the parent class. This makes sense because the child class has the same attributes as the parent class&#8212;and they need to be initialized, too.<\/p>\n<p>The more Pythonic way, however, is to use the <code>super()<\/code> function that makes it easier for you to access the parent class:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">class Dog: def __init__(self, color): self.color = color class CuteDog(Dog): def __init__(self, color): super().__init__(color) self.hairs = True bello = CuteDog('brown')\nprint(bello.hairs)\n# True print(bello.color)\n# brown<\/pre>\n<p>With the help of the <code>super()<\/code> function, you can easily reuse the initializer method of the parent class. <\/p>\n<p>Let&#8217;s have a look at a few related questions.<\/p>\n<h2>Is __ init __ Necessary in Python?<\/h2>\n<p><strong>No. You can simply skip the initializer method. As a result, your class won&#8217;t have any instance attributes directly after its creation. However, you can add instance attributes dynamically at any future point in time. Here&#8217;s an example:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">class Dog: None bello = Dog()\nbello.color = \"blue\"\nprint(bello.color)\n# blue<\/pre>\n<p>How beautiful! You can even create empty classes and &#8220;fill in&#8221; the methods and attributes later in Python.<\/p>\n<h2>What Does __ init __ Return? <\/h2>\n<p><strong>The <code>__init__<\/code> method itself returns nothing. Technically, Python first uses the constructor method <code>Dog()<\/code> before it uses <code>__init__<\/code> to initialize all attributes. Hence, only the constructor returns the newly-created instance.<\/strong><\/p>\n<h2>Can __init__ Return a Value?<\/h2>\n<p><strong>No. The only return value that doesn&#8217;t cause a runtime error is <code>None<\/code>. All other return values cause an error. See the following code example:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">class Dog: def __init__(self, color): self.color = color return 0 bello = Dog(\"blue\")\n# TypeError: __init__() should return None, not 'int'<\/pre>\n<p>So never use any return value in the __init__ method and you&#8217;re good to go.<\/p>\n<h2>Where to Go from Here?<\/h2>\n<p>Thanks for reading through the whole article. You&#8217;ve learned that the <code>__init__<\/code> name is reserved for the Python initializer method that is called within the constructor. <\/p>\n<p>The article requires a thorough understanding of the Python basics. Investing time to learn and study those is vital for your success as a professional coder. <\/p>\n<p>To help people grow their skills in an automated, personalized way, I&#8217;ve created a free Python email course &#8220;Coffee Break Python&#8221; that grows your skill level in a seemingless way. Day after day after day&#8230;<\/p>\n<p><a href=\"https:\/\/blog.finxter.com\/subscribe\/\">Join tens of thousands of Python coders (100% free)!<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>When reading over other people&#8217;s Python code, many beginners are puzzled by the __init__(self) method. What\u2019s its purpose? This article answers this question once and for all. What&#8217;s the purpose of __init__(self) in Python? The reserved Python method __init__() is called the constructor of a class. You can call the constructor method to create an [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[857],"tags":[73,468,528],"class_list":["post-115887","post","type-post","status-publish","format-standard","hentry","category-python-tut","tag-programming","tag-python","tag-tutorial"],"_links":{"self":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/115887","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/comments?post=115887"}],"version-history":[{"count":0,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/115887\/revisions"}],"wp:attachment":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media?parent=115887"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/categories?post=115887"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/tags?post=115887"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}