Polymorphism

The ability to appears in more then one from that is polymorphism

In Python Two type of polymorphism

  • Method Overloading
  • Method Overriding

What is method Overloading in python?

Method name same with changing the number of argument name is call method Overloading in python. but in python Overloading achieve in other hand

Method Overloading not possible in single class

class B10:
	def getName(self,fname):
		print(fname)
	def getName(self,fname,lname):
		 print(fname,lname)
b1=B10()
b1.getName("Ashu")
b1.getName("Arun","singh")
TypeError: getName() missing 1 required positional argument: 'lname'

Method Overloading not possible in is-a relationship

class B10:
	def getName(self,fname):
		print(fname)
class C10(B10):		
	def getName(self,fname,lname):
		 print(fname,lname)
b1=C10()
b1.getName("Ashu")
b1.getName("Arun","singh")
TypeError: getName() missing 1 required positional argument: 'lname'

This way to achieve method overloading in python

class B10:
	def getName(self,f=None,l=None,e=None,m=None):
		print(f,":",l,":",e,":",m)
		
b1=B10()
b1.getName()
b1.getName("Arun")
b1.getName("Arun","singh")
b1.getName("Arun","singh","arun@gmail.com")
b1.getName("Arun","singh","arun@gmail.com","9560822035")
None : None : None : None
Arun : None : None : None
Arun : singh : None : None
Arun : singh : arun@gmail.com : None
Arun : singh : arun@gmail.com : 9560822035

What is method Overriding in python?

Method name same with same argument name is call method Overriding.

Method Overriding possible in single class

if we are overriding then our class method executed

if we are not overriding then parent class method executed

class B10:
	def getName(self,fname):
		print("same to same 1:",fname)
	def getName(self,fname):
		print("same to same 2:",fname)
b1=B10()
b1.getName("Ashu")
b1.getName("Arun")
same to same 2: Ashu
same to same 2: Arun

Method Overriding possible in is-a relationship

class B10:
	def getName(self,fname):
		print("Parent same to same 1:",fname)
class C10(B10):		
	def getName(self,fname):
		print("Child same to same 2:",fname)
b1=C10()
b1.getName("Ashu")
b1.getName("Arun")
Child same to same 2: Ashu
Child same to same 2: Arun

Variable Overriding possible in single class

class B10:
	comName="TCS"
	comName="JTP"
b1=B10()
print(b1.comName)
JTP

Variable Overriding possible in is-a relationship

if we are overriding then our class variable executed

if we are not overriding then parent class variable executed

class B10:
	comName="TCS"
class C10(B10):		
	comName="JTP"
b1=C10()
print(b1.comName)
JTP

Python Interface

class ABC10:
	def getAge(self):
		return 25
	def getName(self):
		return "ninja"
class XYZ10:
	def getAge(self):
		return 26
	def getName(self):
		return "Ashu"	
# create one interface
def getClassObject(obj):
	print(obj.getName())
	print(obj.getAge())
# create the object
xy=XYZ10()
ab=ABC10()
getClassObject(ab) 	
ninja
25