Polymorphism✌


POLYMORPHISM


  • The word polymorphism means having many forms. In programming, polymorphism means the same function name (but different signatures) being uses for different types. 
  • In python, it refers to the use of a single type entity (method, operator or object) to represent different types in different scenarios.
          Example: 
                
                I can be a daughter, a sister, a student, an employee etc.. at the same time depending on place, situations and scenarios.

Overloading

We know that the + operator is used extensively in Python programs. But, it does not have a single usage. In arithmetic, it is used to add the numbers and in strings, it is used for concatenation.
a,b = 2,3
print(a+b)
c,d = 'hello' , 'world'
print(c+d)
>> 5
helloworld


Similarly, the * operator is used extensively in Python programs. But, it does not have a single usage. In arithmetic, it is used to multiply the numbers and in strings, it is used for repetition.
a,b = 2,3
print(a*b)
c= 'hello'
print(c*3)

>> 6
hellohellohello

Method Overloading

Method Overloading is an example of Compile time polymorphism. In this, more than one method of the same class shares the same method name having different signatures. Method overloading is used to add more to the behavior of methods and there is no need for more than one class for method overloading.
Note: Python does not support method overloading. We may overload the methods but can only use the latest defined method. Python does not support constructor overloading as well.

class Student:

  def Details():

    print('I am a student')

  def Details(self,name):

    print('I am {}'.format(name))

  def Details(self,name,marks):

    print('I am {}'.format(name))

    print('I have got {} marks'.format(marks))


stud1=Student()

stud1.Details('Jake',90)

>>I am Jake

    I have got 90 marks

stud1.Details()

TypeError: Details() missing 2 required positional arguments: 'name' and 'marks'

stud1.Details('Jake')

TypeError: Details() missing 1 required positional argument: 'marks'


Method Overriding

Method overriding is an example of run time polymorphism

Method overriding is an ability of any object-oriented programming language that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its super-classes or parent classes. When a method in a subclass has the same name, same parameters or signature and same return type(or sub-type) as a method in its super-class, then the method in the subclass is said to override the method in the super-class.

class Animal:
def move(self):
print(‘move’)
class Cheetah(Animal):
def move(self):
print(‘move fastly’)
class Tortoise(Animal):
def move(self):
print(‘move slowly’)
a = Cheetah()
b = Tortoise()
a.move()
b.move()
move fastly
move slowly



Comments