🐍
Python For Starters
  • Overview
  • Python for starters
  • Content
  • Foreword
  • Introduction To Python
    • Python Installation
    • Variables
    • Python Data Types
    • Python Data Structures
    • Python numbers
    • Python strings
    • Python Boolean
    • Python constants
    • Python Comments
    • Type Conversion
    • Control flow in python
  • Python Functions
    • Function Definition
    • Function Parameter
    • Recursive Functions
    • Using Global Variables in Functions
    • Lambda Functions
  • What are Data Structures
    • Python Lists
    • Python Tuples
    • Python Dictionaries
    • Python Sets
    • Iterable in python
    • Python Map, Filter & Reduce Functions
  • Error handling in Python
  • Loop ... Else Clause, Partial Functions & Type Hints
    • Partial Functions
    • Type Hints
  • Python Modules
  • Python Libraries & Packages
    • Python Packages
  • Directory & IO
    • Python IO Module
  • Pyenv
  • Virtual Environments
    • Pipenv
    • Virtualenv
  • Object Oriented Programming in Python
    • Class
    • Class Methods
    • Python Class Inheritance
    • Python Class Polymorphism
    • Python special methods
  • Appendix
  • Contributing
Powered by GitBook
On this page
  1. Object Oriented Programming in Python

Python Class Polymorphism

Polymorphism is the process of using an operator or function in different ways for different data input. In practical terms, polymorphism means that if class B inherits from class A, it doesn't have to inherit everything about class A; it can do some of the things that class A does differently.

# basic_polymorphism.py

a = "alfa"
b = (1, 2, 3, 4)
c = ['o', 'm', 'e', 'g', 'a']

print(a[2])
print(b[1])
print(c[3])

Python uses polymorphism extensively in built-in types. Here we use the same indexing operator for three different data types.

Polymorphism is mostly used when dealing with inheritance.

# polymorphism.py

class Animal:
   def __init__(self, name=''):
      self.name = name

   def talk(self):
      pass

class Cat(Animal):
   def talk(self):
      print("Meow!")

class Dog(Animal):
   def talk(self):
      print("Woof!")

a = Animal()
a.talk()

c = Cat("Missy")
c.talk()

d = Dog("Rocky")
d.talk()

Here we have two species: a dog and a cat. Both are animals. The Dog class and the Cat class inherit the Animal class. They have a talk method, which gives different output for them.

$ ./polymorphism.py 

Meow!
Woof!
PreviousPython Class InheritanceNextPython special methods

Last updated 2 years ago