What is Polymorphism : The word polymorphism means having many forms. In programming, polymorphism means same function name (but different signatures) being uses for different types.
Example of inbuilt polymorphic functions :
# Python program to demonstrate in-built poly- # morphic functions # len() being used for a string print(len("geeks"))# len() being used for a list print(len([10, 20, 30]))
5
3
Examples of user defined polymorphic functions :
# A simple Python function to demonstrate # Polymorphism defadd(x,y,z=0): return x + y+z # Driver code print(add(2, 3))print(add(2, 3, 4))
5
9
Polymorphism with class methods:
classIndia(): defcapital(self): print("New Delhi is the capital of India.")deflanguage(self): print("Hindi is the most widely spoken language of India.")deftype(self): print("India is a developing country.")classUSA(): defcapital(self): print("Washington, D.C. is the capital of USA.")deflanguage(self): print("English is the primary language of USA.")deftype(self): print("USA is a developed country.")obj_ind =India()obj_usa =USA()for country in (obj_ind, obj_usa): country.capital() country.language() country.type()
New Delhi is the capital of India.
Hindi is the most widely spoken language of India.
India is a developing country.
Washington, D.C. is the capital of USA.
English is the primary language of USA.
USA is a developed country.
Polymorphism with Inheritance:
classBird: defintro(self): print("There are many types of birds.")defflight(self): print("Most of the birds can fly but some cannot.")classsparrow(Bird): defflight(self): print("Sparrows can fly.")classostrich(Bird): defflight(self): print("Ostriches cannot fly.")obj_bird =Bird()obj_spr =sparrow()obj_ost =ostrich()obj_bird.intro()obj_bird.flight()obj_spr.intro()obj_spr.flight()obj_ost.intro()obj_ost.flight()
There are many types of birds.
Most of the birds can fly but some cannot.
There are many types of birds.
Sparrows can fly.
There are many types of birds.
Ostriches cannot fly.
Polymorphism with a Function and objects:
classIndia(): defcapital(self): print("New Delhi is the capital of India.")deflanguage(self): print("Hindi is the most widely spoken language of India.")deftype(self): print("India is a developing country.")classUSA(): defcapital(self): print("Washington, D.C. is the capital of USA.")deflanguage(self): print("English is the primary language of USA.")deftype(self): print("USA is a developed country.")deffunc(obj): obj.capital() obj.language() obj.type()obj_ind =India()obj_usa =USA()func(obj_ind)func(obj_usa)
New Delhi is the capital of India.
Hindi is the most widely spoken language of India.