{"id":78373,"date":"2020-04-19T10:00:34","date_gmt":"2020-04-19T04:30:34","guid":{"rendered":"https:\/\/techvidvan.com\/tutorials\/?p=78373"},"modified":"2024-08-22T20:13:28","modified_gmt":"2024-08-22T14:43:28","slug":"python-polymorphism","status":"publish","type":"post","link":"https:\/\/techvidvan.com\/tutorials\/python-polymorphism\/","title":{"rendered":"Polymorphism in Python with Examples"},"content":{"rendered":"<p>One of the important concepts under Object-oriented programming is <strong>Polymorphism<\/strong>.<\/p>\n<p>In this article, we\u2019ll see what is <strong>polymorphism in python<\/strong>, how python polymorphism works.<\/p>\n<p>We will also learn how we can implement it in our own <strong>Python programs<\/strong>.<\/p>\n<h3>What is Polymorphism in Python?<\/h3>\n<p>Polymorphism gives you the ability to <strong>represent objects<\/strong> of different types using a <strong>single interface<\/strong>.<\/p>\n<p>A real-life example is <strong>You<\/strong>.<\/p>\n<p>You <strong>act<\/strong> as a <strong>student<\/strong> when you are at <strong>college<\/strong>, you act like a <strong>son\/daughter<\/strong> when you\u2019re at <strong>home<\/strong>, you act like a <strong>friend<\/strong> when you\u2019re surrounded by your <strong>friends<\/strong>.<\/p>\n<p>Now the <strong>analogy<\/strong> here is, <strong>different personalities<\/strong> of that of a <strong>student<\/strong>, a<strong> son\/daughter<\/strong>, a <strong>friend<\/strong> are all <strong>analogous<\/strong> to <strong>objects<\/strong> of <strong>different types<\/strong>.<\/p>\n<p>And a <strong>single interface (i.e., you)<\/strong> <strong>represents<\/strong> all these <strong>different types( i.e. your different personalities)<\/strong>.<\/p>\n<h3>Understanding Polymorphism in Python<\/h3>\n<p>Python can implement <strong>polymorphism<\/strong> in many different ways. Python, like many other languages, also provides <strong>built-in implementations<\/strong> of Polymorphism.<\/p>\n<p>Let\u2019s look at the examples that illustrate built-in implementations of polymorphism in <strong>Python<\/strong>.<\/p>\n<p>Later in this article, we\u2019ll see the various ways in which we can implement <strong>Polymorphism<\/strong> in our <strong>own programs<\/strong>.<\/p>\n<h4>Built-in implementation of Polymorphism<\/h4>\n<p><strong>a. Polymorphism in \u2018+\u2019 operator<\/strong><\/p>\n<ul>\n<li>You might have used the<strong> \u2018+\u2019 arithmetic<\/strong> python operator <strong>multiple times<\/strong> in your programs.<\/li>\n<li>And chances are, you might have used it with <strong>multiple different types<\/strong>.<\/li>\n<li>This right here is an implementation of <strong>polymorphism<\/strong> in Python.<\/li>\n<li>You use the same <strong>+ symbol<\/strong> whether you want to <strong>add two integers<\/strong>, or <strong>concatenate two strings<\/strong>, or <strong>extend two lists<\/strong>.<\/li>\n<li>The + operator acts differently depending on the type of objects it is <strong>operating upon<\/strong>.<\/li>\n<\/ul>\n<p><strong>For integers, it performs arithmetic addition and returns an integer:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">&gt;&gt;&gt; x = 1 + 2\r\n&gt;&gt;&gt; print(x)<\/pre>\n<p>Output:<\/p>\n<div class=\"code-output\">3<br \/>\n&gt;&gt;&gt;<\/div>\n<p><strong>Whereas for strings, it concatenates them and returns a new string:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">&gt;&gt;&gt; x = \"TechVidvan says \" + \"Hello\"\r\n&gt;&gt;&gt; print(x)<\/pre>\n<p>Output:<\/p>\n<div class=\"code-output\">&#8216;TechVidvan says Hello&#8217;<br \/>\n&gt;&gt;&gt;<\/div>\n<p><strong>And for two lists, it returns a new list which contains elements of both the original lists:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">&gt;&gt;&gt; x = [1, 2, 3] + [10, \u2018TechVidvan\u2019]\r\n&gt;&gt;&gt; print(x)<\/pre>\n<p>Output:<\/p>\n<div class=\"code-output\">[1, 2, 3, 10, \u2018TechVidvan\u2019]<br \/>\n&gt;&gt;&gt;<\/div>\n<p><strong>b. Polymorphism in built-in method<\/strong><\/p>\n<ul>\n<li>Python also implements <strong>polymorphism<\/strong> using <strong>methods<\/strong>.<\/li>\n<li>For instance, take the<strong> len()<\/strong> method that returns the <strong>length<\/strong> of an <strong>object<\/strong>.<\/li>\n<li>The<strong> len()<\/strong> method is <strong>capable<\/strong> of <strong>processing objects<\/strong> of different <strong>data types<\/strong>.<\/li>\n<li>Let\u2019s look at the code example below:<\/li>\n<\/ul>\n<p><strong>For a list, it returns the number of elements in the list.<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">&gt;&gt;&gt; l = [1, 2, 3, 4, 5]\r\n&gt;&gt;&gt; length = len(l)\r\n&gt;&gt;&gt; print(length)<\/pre>\n<p>Output:<\/p>\n<div class=\"code-output\">5<br \/>\n&gt;&gt;&gt;<\/div>\n<p><strong>For a string, it returns the number of characters within it.<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">&gt;&gt;&gt; s = \u201cTechVidvan\u201d\r\n&gt;&gt;&gt; length = len(s)\r\n&gt;&gt;&gt; print(length)<\/pre>\n<p>Output:<\/p>\n<div class=\"code-output\">10<br \/>\n&gt;&gt;&gt;<\/div>\n<p><strong>For python dictionary, it returns the number of keys.<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">&gt;&gt;&gt; d = {1: \u201cArchie\u201d, 2: \u201cBrady\u201d, 3: \u201cCharlie\u201d}\r\n&gt;&gt;&gt; length = len(d)\r\n&gt;&gt;&gt; print(length)<\/pre>\n<p><strong>Output<\/strong>:<\/p>\n<div class=\"code-output\">3<br \/>\n&gt;&gt;&gt;<\/div>\n<p>We have got a <strong>high-level view<\/strong> of what <strong>polymorphism<\/strong> is and how <strong>Python implements<\/strong> it.<\/p>\n<p>Let\u2019s now dive into how we can <strong>implement polymorphism<\/strong> ourselves in our <strong>Python program<\/strong>.<\/p>\n<h4>Polymorphism in user-defined methods<\/h4>\n<p>In the below example, we have <strong>two classes<\/strong> <strong>\u2018Rectangle\u2019<\/strong> and <strong>\u2018Square\u2019<\/strong>. Both these classes have a method definition <strong>\u2018area\u2019<\/strong>, that calculates the area of the <strong>corresponding shapes<\/strong>.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">class Rectangle:\r\n    def __init__(self, length, breadth):\r\n        self.l = length\r\n        self.b = breadth\r\n\r\n    def area(self):\r\n        return self.l * self.b\r\n\r\nclass Square:\r\n    def __init__(self, side):\r\n        self.s = side\r\n\r\n    def area(self):\r\n        return self.s ** 2\r\n\r\nrec = Rectangle(10, 20)\r\nsqu = Square(10)\r\n\r\nprint(\"Area of rectangle is: \", rec.area())\r\nprint(\"Area of square is: \", squ.area())<\/pre>\n<p><strong>Output<\/strong>:<\/p>\n<div class=\"code-output\">Area of rectangle is: 200<br \/>\nArea of square is: 100<br \/>\n&gt;&gt;&gt;<\/div>\n<p>Here, we implemented <strong>polymorphism<\/strong> using the <strong>method area()<\/strong>. This method works on <strong>objects<\/strong> of the <strong>types<\/strong>&#8211; <strong>Rectangle<\/strong> and <strong>Square<\/strong>. And it operates <strong>differently<\/strong> on <strong>objects<\/strong> of <strong>different classes<\/strong>.<\/p>\n<p>We can also achieve <strong>polymorphism<\/strong> with <strong>inheritance<\/strong>.<\/p>\n<p>Let\u2019s see how.<\/p>\n<h4>Polymorphism with Inheritance in python<\/h4>\n<p>A <strong>child class<\/strong> <strong>inherits<\/strong> all the <strong>attributes<\/strong> and <strong>methods<\/strong> of its <strong>parent class<\/strong>. But we can provide <strong>one<\/strong> or <strong>more<\/strong> <strong>methods<\/strong> with a <strong>different<\/strong> <strong>method<\/strong> definition within the <strong>child class<\/strong>.<\/p>\n<p>We call this process <strong>\u201cmethod overriding\u201d<\/strong> and such methods <strong>\u201coverridden\u201d<\/strong> methods.<\/p>\n<p>Overridden methods have the exact same external interface (method name, number, and type of method parameters) as the parent class\u2019s method but have a different internal implementation. This allows the child class to tailor or extend the functionality of the parent class to meet specific needs.<\/p>\n<p>By using method overriding, we achieve polymorphism, where the same method name can exhibit different behaviors depending on the object that invokes it. This enhances code reusability and makes our programs more flexible and easier to maintain.<\/p>\n<p>Let\u2019s look at a very simple example:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">#parent class\r\nclass Human:\r\n    def who_am_i(self):\r\n        print(\"I am a Human\")\r\n\r\n#child class\r\nclass Teacher(Human):\r\n    def who_am_i(self):\r\n        print(\"I am a Teacher\")\r\n\r\n\r\nt = Teacher()\r\nt.who_am_i()<\/pre>\n<p><strong>Output<\/strong>:<\/p>\n<div class=\"code-output\">I am a Teacher<\/div>\n<p>Here, we implement polymorphism by <strong>overriding<\/strong> the method <strong>who_am_i()<\/strong> and providing it with a <strong>different implementation<\/strong> in the child class Teacher.<\/p>\n<h3>Summary<\/h3>\n<p>Hope you got a clear understanding of what <strong>polymorphism<\/strong> is and how do we <strong>implement<\/strong> it in Python. You\u2019ll come across Polymorphism in <strong>many languages<\/strong> that support <strong>object-oriented programming paradigm<\/strong>.<\/p>\n<p>So make sure to be thorough while understanding it.<\/p>\n<p>In other languages, we can achieve polymorphism with method <strong>overloading<\/strong> too, but <strong>Python<\/strong> <strong>does not support<\/strong> it.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>One of the important concepts under Object-oriented programming is Polymorphism. In this article, we\u2019ll see what is polymorphism in python, how python polymorphism works. We will also learn how we can implement it in&#46;&#46;&#46;<\/p>\n","protected":false},"author":1,"featured_media":78374,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1053],"tags":[2475,2476,2477,2478],"class_list":["post-78373","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-python","tag-polymorphism-in-python","tag-polymorphism-in-python-example","tag-python-polymorphism","tag-python-polymorphism-example"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.7 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Polymorphism in Python with Examples - TechVidvan<\/title>\n<meta name=\"description\" content=\"Learn polymorphism in Python - What is polymorphism, built in implementation of polymorphism, polymorphism with inheritance,\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/techvidvan.com\/tutorials\/python-polymorphism\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Polymorphism in Python with Examples - TechVidvan\" \/>\n<meta property=\"og:description\" content=\"Learn polymorphism in Python - What is polymorphism, built in implementation of polymorphism, polymorphism with inheritance,\" \/>\n<meta property=\"og:url\" content=\"https:\/\/techvidvan.com\/tutorials\/python-polymorphism\/\" \/>\n<meta property=\"og:site_name\" content=\"TechVidvan\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/TechVidvan\/\" \/>\n<meta property=\"article:published_time\" content=\"2020-04-19T04:30:34+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2024-08-22T14:43:28+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/04\/polymorphism-in-python.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"802\" \/>\n\t<meta property=\"og:image:height\" content=\"420\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"TechVidvan Team\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:site\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"TechVidvan Team\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"4 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Polymorphism in Python with Examples - TechVidvan","description":"Learn polymorphism in Python - What is polymorphism, built in implementation of polymorphism, polymorphism with inheritance,","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:\/\/techvidvan.com\/tutorials\/python-polymorphism\/","og_locale":"en_US","og_type":"article","og_title":"Polymorphism in Python with Examples - TechVidvan","og_description":"Learn polymorphism in Python - What is polymorphism, built in implementation of polymorphism, polymorphism with inheritance,","og_url":"https:\/\/techvidvan.com\/tutorials\/python-polymorphism\/","og_site_name":"TechVidvan","article_publisher":"https:\/\/www.facebook.com\/TechVidvan\/","article_published_time":"2020-04-19T04:30:34+00:00","article_modified_time":"2024-08-22T14:43:28+00:00","og_image":[{"width":802,"height":420,"url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/04\/polymorphism-in-python.jpg","type":"image\/jpeg"}],"author":"TechVidvan Team","twitter_card":"summary_large_image","twitter_creator":"@vidvantech","twitter_site":"@vidvantech","twitter_misc":{"Written by":"TechVidvan Team","Est. reading time":"4 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/techvidvan.com\/tutorials\/python-polymorphism\/#article","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/python-polymorphism\/"},"author":{"name":"TechVidvan Team","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22"},"headline":"Polymorphism in Python with Examples","datePublished":"2020-04-19T04:30:34+00:00","dateModified":"2024-08-22T14:43:28+00:00","mainEntityOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/python-polymorphism\/"},"wordCount":756,"commentCount":0,"publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/python-polymorphism\/#primaryimage"},"thumbnailUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/04\/polymorphism-in-python.jpg","keywords":["Polymorphism in Python","polymorphism in python example","python polymorphism","python polymorphism example"],"articleSection":["Python Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/techvidvan.com\/tutorials\/python-polymorphism\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/techvidvan.com\/tutorials\/python-polymorphism\/","url":"https:\/\/techvidvan.com\/tutorials\/python-polymorphism\/","name":"Polymorphism in Python with Examples - TechVidvan","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/#website"},"primaryImageOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/python-polymorphism\/#primaryimage"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/python-polymorphism\/#primaryimage"},"thumbnailUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/04\/polymorphism-in-python.jpg","datePublished":"2020-04-19T04:30:34+00:00","dateModified":"2024-08-22T14:43:28+00:00","description":"Learn polymorphism in Python - What is polymorphism, built in implementation of polymorphism, polymorphism with inheritance,","breadcrumb":{"@id":"https:\/\/techvidvan.com\/tutorials\/python-polymorphism\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/techvidvan.com\/tutorials\/python-polymorphism\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/python-polymorphism\/#primaryimage","url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/04\/polymorphism-in-python.jpg","contentUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/04\/polymorphism-in-python.jpg","width":802,"height":420,"caption":"Polymorphism in Python"},{"@type":"BreadcrumbList","@id":"https:\/\/techvidvan.com\/tutorials\/python-polymorphism\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/techvidvan.com\/tutorials\/"},{"@type":"ListItem","position":2,"name":"Polymorphism in Python with Examples"}]},{"@type":"WebSite","@id":"https:\/\/techvidvan.com\/tutorials\/#website","url":"https:\/\/techvidvan.com\/tutorials\/","name":"TechVidvan Blogs","description":"","publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/techvidvan.com\/tutorials\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/techvidvan.com\/tutorials\/#organization","name":"TechVidvan","url":"https:\/\/techvidvan.com\/tutorials\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/","url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","contentUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","width":200,"height":50,"caption":"TechVidvan"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/TechVidvan\/","https:\/\/x.com\/vidvantech"]},{"@type":"Person","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22","name":"TechVidvan Team","description":"The TechVidvan Team delivers practical, beginner-friendly tutorials on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our experts are here to help you upskill and excel in today\u2019s tech industry."}]}},"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/78373","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/comments?post=78373"}],"version-history":[{"count":2,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/78373\/revisions"}],"predecessor-version":[{"id":447695,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/78373\/revisions\/447695"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media\/78374"}],"wp:attachment":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media?parent=78373"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/categories?post=78373"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/tags?post=78373"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}