{"id":955,"date":"2026-11-19T18:44:13","date_gmt":"2026-11-19T18:44:13","guid":{"rendered":"https:\/\/www.askpython.com\/?p=955"},"modified":"2026-11-19T18:44:13","modified_gmt":"2026-11-19T18:44:13","slug":"polymorphism-in-python","status":"publish","type":"post","link":"https:\/\/www.askpython.com\/python\/oops\/polymorphism-in-python","title":{"rendered":"Polymorphism in Python: Examples and Use"},"content":{"rendered":"<!-- article-type: tutorial -->\n<!-- receipt-backed-first-person -->\n\n<p class=\"wp-block-paragraph\">Writing Python code that works with different objects starts with choosing the operation the code will call. Polymorphism lets one piece of calling code use the same operation with different objects, while each object supplies its own response.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This article shows how one function can call the same method on different objects and how an abstract base class can require that method.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">TL;DR<\/h2>\n\n\n<p class=\"wp-block-paragraph\">Polymorphism lets one piece of calling code use different objects through the same operation, while each object supplies its own response.<\/p>\n\n\n<ul class=\"wp-block-list\"><li>A function that calls render() can work with unrelated objects that provide that method.<\/li><li>Inheritance allows a subclass to override a method, but a shared parent class is not required for duck typing.<\/li><li>Python does not select same-named methods by argument count. Use defaults or variadic parameters when that is the goal.<\/li><\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">What Is Polymorphism in Python?<\/h2>\n\n\n<p class=\"wp-block-paragraph\">Polymorphism lets a caller use a common operation on objects that respond in their own way.<\/p>\n\n\n<p class=\"wp-block-paragraph\">An interface is the operation the caller expects, and publish() expects report.render(). TextReport returns plain text, while JsonReport returns structured text, and both results can be printed. A different return type could break a later consumer even though the method call succeeds.<\/p>\n\n\n<p class=\"wp-block-paragraph\">Duck typing relies on the methods an object supplies without requiring it to inherit from a named base class. The report classes can therefore remain unrelated.<\/p>\n\n\n<p class=\"wp-block-paragraph\">Use <a href=\"https:\/\/docs.python.org\/3\/library\/typing.html\" target=\"_blank\" rel=\"noopener\">typing.Protocol<\/a> when a static checker should verify the methods a consumer expects. A runtime-checkable protocol only checks attribute presence, not whether a method&#8217;s signature or return value is correct.<\/p>\n\n\n<h3 class=\"wp-block-heading\">Ways to recognize it<\/h3>\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><thead><tr><th>Mechanism<\/th><th>What varies<\/th><th>Example<\/th><\/tr><\/thead><tbody><tr><td>Duck typing<\/td><td>Object implementation behind a method call<\/td><td>Two report objects implement render()<\/td><\/tr><tr><td>Overriding<\/td><td>Subclass method selected for an instance<\/td><td>DetailedReport replaces describe()<\/td><\/tr><tr><td>Operator behavior<\/td><td>Operation chosen for operand types<\/td><td>Numbers add and strings concatenate<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n<p class=\"wp-block-paragraph\">The built-in len() requests a length through the data model, and a custom class can provide one with __len__() returning a non-negative integer.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">How to Use Polymorphism in Python Step by Step<\/h2>\n\n\n<p class=\"wp-block-paragraph\">Start from the operation the consumer needs, then give it objects that implement that operation. The program below sends two separate report classes through one publishing function and then checks an inherited override.<\/p>\n\n\n<h3 class=\"wp-block-heading\">Step 1: Define the shared operation<\/h3>\n\n\n<p class=\"wp-block-paragraph\">The file defines TextReport and JsonReport with the same method name. It then defines a base\/subclass pair and two deliberate failure cases.<\/p>\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nclass TextReport:\n    def render(self):\n        return &quot;text report&quot;\n\n\nclass JsonReport:\n    def render(self):\n        return &quot;JSON report&quot;\n\n\ndef publish(report):\n    print(report.render())\n\n\nfor report in (TextReport(), JsonReport()):\n    publish(report)\n\n\nclass Base:\n    def describe(self):\n        return &quot;base description&quot;\n\n\nclass Detailed(Base):\n    def describe(self):\n        return &quot;detailed description&quot;\n\n\nprint(Detailed().describe())\n\n\nclass BrokenReport:\n    pass\n\n\ntry:\n    publish(BrokenReport())\nexcept AttributeError as error:\n    print(f&quot;{type(error).__name__}: {error}&quot;)\n\n\nclass Adder:\n    def add(self, first, second):\n        return first + second\n\n\ntry:\n    Adder().add(1, 2, 3)\nexcept TypeError as error:\n    print(f&quot;{type(error).__name__}: {error}&quot;)\n<\/pre><\/div>\n\n<p class=\"wp-block-paragraph\">Run the saved file with python3 polymorphism_demo.py. Its complete output is:<\/p>\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\ntext report\nJSON report\ndetailed description\nAttributeError: &#039;BrokenReport&#039; object has no attribute &#039;render&#039;\nTypeError: Adder.add() takes 3 positional arguments but 4 were given\n<\/pre><\/div>\n\n<figure class=\"wp-block-image aligncenter size-full\"><img decoding=\"async\" src=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2026\/11\/polymorphism-demo.png\" alt=\"Terminal output showing two report objects, an override, and missing-method errors\"\/><figcaption>The command output shows both report responses, the override, and two caught errors.<\/figcaption><\/figure>\n\n\n<p class=\"wp-block-paragraph\">I ran python3 polymorphism_demo.py and saw \u201ctext report\u201d followed by \u201cJSON report.\u201d The next line was \u201cdetailed description.\u201d The output then showed the two exception messages, and the command ended with status 0.<\/p>\n\n\n<p class=\"wp-block-paragraph\">Detailed inherits Base and overrides describe(). Python checks Detailed before its parent class during method lookup.<\/p>\n\n\n<h3 class=\"wp-block-heading\">Step 2: Enforce a required method with an ABC<\/h3>\n\n\n<p class=\"wp-block-paragraph\">An abstract base class can reject incomplete subclasses at instantiation. Define the required operation as abstract, then implement it in each concrete class.<\/p>\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nfrom abc import ABC, abstractmethod\n\n\nclass Renderer(ABC):\n    @abstractmethod\n    def render(self):\n        raise NotImplementedError\n\n\nclass TextRenderer(Renderer):\n    def render(self):\n        return &quot;text report&quot;\n\n\nclass UnfinishedRenderer(Renderer):\n    pass\n\n\nprint(TextRenderer().render())\n\nfor renderer_type in (Renderer, UnfinishedRenderer):\n    try:\n        renderer_type()\n    except TypeError as error:\n        print(f&quot;{renderer_type.__name__}: {error}&quot;)\n<\/pre><\/div>\n\n<p class=\"wp-block-paragraph\">Run python3 abc_contract_demo.py to check the incomplete classes. The program prints:<\/p>\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\ntext report\nRenderer: Can&#039;t instantiate abstract class Renderer with abstract method render\nUnfinishedRenderer: Can&#039;t instantiate abstract class UnfinishedRenderer with abstract method render\n<\/pre><\/div>\n\n<figure class=\"wp-block-image aligncenter size-full\"><img decoding=\"async\" src=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2026\/11\/abc-contract-demo.png\" alt=\"Terminal output showing an abstract renderer and an incomplete subclass rejected at instantiation\"\/><figcaption>The terminal shows a concrete renderer succeeding while abstract classes cannot be instantiated.<\/figcaption><\/figure>\n\n\n<p class=\"wp-block-paragraph\">The output distinguishes an implemented renderer from the abstract base and its unfinished child. Use this check for an extension contract that should fail before the object reaches a later method call. That moves detection to construction.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Edge Cases: Missing Methods and Overloading<\/h2>\n\n\n<p class=\"wp-block-paragraph\">The captured AttributeError shows what happens when an object lacks the method its consumer calls.<\/p>\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><thead><tr><th>Case<\/th><th>Symptom<\/th><th>Response<\/th><\/tr><\/thead><tbody><tr><td>Object has no render()<\/td><td>AttributeError at the call<\/td><td>Supply a compatible object or validate the boundary<\/td><\/tr><tr><td>Extra method argument<\/td><td>TypeError reports too many positional arguments<\/td><td>Use a default or *args when the method should accept variable input<\/td><\/tr><tr><td>Subclass method differs<\/td><td>Override runs in place of the base method<\/td><td>Keep the same caller-facing meaning for the operation<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n<p class=\"wp-block-paragraph\">Handle a contract mismatch at the boundary where objects enter the program. Tests can pass a compatible alternative and an incomplete object to check both the response and the failure path. The demonstration catches exceptions to print their messages, but catching every AttributeError in production can hide a defect inside render().<\/p>\n\n\n<p class=\"wp-block-paragraph\">The first failure was AttributeError: &#8216;BrokenReport&#8217; object has no attribute &#8216;render&#8217;. The consumer assumed its input had the method, and the object did not provide it.<\/p>\n\n\n<p class=\"wp-block-paragraph\">A class namespace keeps one binding for each method name. A later definition replaces the earlier one.<\/p>\n\n\n<p class=\"wp-block-paragraph\">The <a href=\"https:\/\/docs.python.org\/3\/library\/typing.html\" target=\"_blank\" rel=\"noopener\">typing module&#8217;s @overload<\/a> declarations describe alternate signatures for static type checkers, while one concrete function handles those cases at runtime.<\/p>\n\n\n<p class=\"wp-block-paragraph\">I passed three values to the two-parameter add() method and got TypeError: Adder.add() takes 3 positional arguments but 4 were given. The count includes self, which Python supplies for a bound instance method. The fix depends on intent: add a default for an optional value, or accept *numbers and process the sequence.<\/p>\n\n\n<p class=\"wp-block-paragraph\">For unsupported operands, a custom __add__() can return NotImplemented to let Python try the right operand&#8217;s reflected method, as specified by the data model.<\/p>\n\n\n<p class=\"wp-block-paragraph\">An ABC lets a library define a contract for extension classes, and instantiation fails until a child supplies its abstract methods. Its concrete helpers can call those operations. Registering a virtual subclass changes subclass checks but adds no methods or method lookup, so use an ABC when enforcement matters.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Conclusion<\/h2>\n\n\n<p class=\"wp-block-paragraph\">Choose a mechanism that makes the required operation clear where objects enter the function. Read <a href=\"https:\/\/www.askpython.com\/python\/oops\/python-classes-objects\">Python classes and objects<\/a> for class basics and <a href=\"https:\/\/www.askpython.com\/python\/oops\/inheritance-in-python\">inheritance in Python<\/a> for subclass behavior. The <a href=\"https:\/\/www.askpython.com\/python\/operator-overloading-in-python\">operator overloading in Python<\/a> guide covers special methods.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">FAQ<\/h2>\n\n\n<p class=\"wp-block-paragraph\">These answers separate the related terms that often appear together in Python OOP tutorials.<\/p>\n\n<div id=\"rank-math-faq\" class=\"rank-math-block\">\n<div class=\"rank-math-list \">\n<div id=\"faq-question-1784440000001\" class=\"rank-math-list-item\">\n<h3 class=\"rank-math-question \">Is inheritance required for polymorphism in Python?<\/h3>\n<div class=\"rank-math-answer \">\n\n<p>No. Duck typing lets unrelated objects respond to the same operation without sharing a base class. Inheritance is one way to share and override behavior.<\/p>\n\n<\/div>\n<\/div>\n<div id=\"faq-question-1784440000002\" class=\"rank-math-list-item\">\n<h3 class=\"rank-math-question \">Does Python support method overloading by signature?<\/h3>\n<div class=\"rank-math-answer \">\n\n<p>Ordinary same-named method definitions do not dispatch by argument signature. Use defaults, *args, or a dispatch tool when the behavior calls for argument-based variation.<\/p>\n\n<\/div>\n<\/div>\n<div id=\"faq-question-1784440000003\" class=\"rank-math-list-item\">\n<h3 class=\"rank-math-question \">What does polymorphism look like in a Python function?<\/h3>\n<div class=\"rank-math-answer \">\n\n<p>A function calls one method, such as render(), on each supplied object. Each object&#8217;s implementation determines the response.<\/p>\n\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n","protected":false},"excerpt":{"rendered":"<p>Writing Python code that works with different objects starts with choosing the operation the code will call. Polymorphism lets one piece of calling code use the same operation with different objects, while each object supplies its own response. This article shows how one function can call the same method on different objects and how an [&hellip;]<\/p>\n","protected":false},"author":4,"featured_media":72576,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[11],"tags":[],"class_list":["post-955","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-oops"],"_links":{"self":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/955","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/users\/4"}],"replies":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/comments?post=955"}],"version-history":[{"count":0,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/955\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/media\/72576"}],"wp:attachment":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/media?parent=955"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/categories?post=955"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/tags?post=955"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}