Polymorphism In Python



You might have used many built-in methods or defined many class methods in python, so let’s dive deep into their functionality and a concept of object oriented programming that is polymorphism today.

What is Polymorphism
Common examples of Polymorphism
Polymorphism between functions and objects
Polymorphism within inheritance
Method Overriding
Run time and Compile time polymorphism in python 

Polymorphism is when a same piece of code works differently at different places that is with many forms.In object oriented programming paradigm, a method defined in Base class can be used with the same name in the various subclasses with different purposes.

A common example where you would use is to calculate the length of different objects.For instance, the same built-in len() method is used to return the length of a string , length of a list or length of a dictionary, similarly the type() function works differently for different objects.

Polymorphism can be among functions and objects or amongst class methods or in classes amongst inheritance.

Polymorphism between functions and objects.

For instance, let’s create a common function driver for two classes and pass objects of different classes to it, but call the same methods for the objects.

class Manager:

      def type(self):

          print(“Full time Employee”)


     def bonus(self):

           print(“Eligible for bonus”)

 

class Writer:

     def type(self):

           print(“Part Time Employee”)


     def bonus(self):

           print(“Not eligible for bonus”)


def driver(obj):

      obj.type()

      obj.bonus()


obj_1 = Manager()

obj_2 = Writer()

driver(obj_1)

driver(obj_2)

Output

Full time Employee

Eligible for bonus

Part Time Employee

Not eligible for bonus

Checkout this Python Online Training by FITA. FITA provides a complete Python course where you will be building real-time projects like Bitly and Twitter bundled with Django, placement support and certification at an affordable price.

Polymorphism within Inheritance

In inheritance, polymorphism takes place between a base class and a derived or sub class.Methods with the same name can be used in base and derived class, and also overriding the function of the base class by redefining it in derived class is known as Method overriding.This is mostly done when when the child class is required to change a feature of parent class.

Here is an example for deeper understanding

class FullTimeEmployee:


      def __init__(self, name, position, hours, salary):

          self.name = name

          self.position = position

          self.hours = hours

          self.salary = salary


      def bonus(self):

          return (self.salary * 0.5)


class PartTimeEmployee(FullTimeEmployee):

      def __init__(self, name, position, hours, salary):

          super().__init__(name, position, hours, salary)


def inc_bonus(object):

     x = object.bonus()

     print(f'{object.name}/’s bonus will be {x}’)


emp_1 = FullTimeEmployee(‘Atufa’, ‘Frontend Developer’, 6, 1000)

emp_2 = PartTimeEmployee(‘Shireen’, ‘Content Writer’, 8, 2000)


print(inc_bonus(emp_1))

print(inc_bonus(emp_2))

The super() charge and the subclassing will have the same bonus method, which calculates 50 percent bonus for either type of employee.

Here is the output for the example program

Atufa’s bonus will be 500.0


Shireen’s bonus will be 1000.0

Method Overriding

We don’t want to give a 50 percent bonus to a part time employee, thus we will use an overriding method to give a 10 percent bonus for a part time employee.

class FullTimeEmployee:


def __init__(self, name, position, hours, salary):

    self.name = name

    self.position = position

    self.hours = hours

    self.salary = salary


def bonus(self):

    return self.salary * 0.5


class PartTimeEmployee(FullTimeEmployee):

      def __init__(self, name, position, hours, salary):

          super().__init__(name, position, hours, salary)


     def bonus(self):

          return self.salary * 0.1


# common interface

     def inc_bonus(object):

         x = object.bonus()

         print(f'{object.name}\’s bonus will be {x}’)


# instantiating objects for the two classes

emp_1 = FullTimeEmployee(‘Atufa’, ‘Frontend Developer’, 6, 1000)

emp_2 = PartTimeEmployee(‘Shireen’, ‘Content Writer’, 8, 2000)


# passing the objects to common interface

print(inc_bonus(emp_1))

print(inc_bonus(emp_2))

Now the output with the same inputs will be

Atufa’s bonus will be 500.0


Shireen’s bonus will be 200.0

Run Time And Compile Time Polymorphism In Python

In the above examples, the interpreter chose the function which comes last i.e, in overriding and forgets about the previously defined method in case of calculating bonus.This is known as run time polymorphism.

Python unlike many other famous programming languages such as java, c++ , go does not support compile time polymorphism because it doesn’t use function arguments for method signature.

Operator Overloading

In python, the operator behaves differently based on the type of object, this also a type of polymorphism, but as operator overloading.

For example

+ (operator) sums up two numbers or concatenates the two or more incase of strings.

>> 2+3

5

>> ‘2’+’3′

23

* multiplies two numbers or repeats the object in case of use between strings.

>> 2*3

6

>> ‘2’*3

222

This was all about Polymorphism and its types and implementation in python..To get in-depth knowledge of Python along with its various applications and real-time projects, you can enroll in Python Training in Chennai or Python Training in Bangalore by FITA at an affordable price, which includes real time projects with certification, support and career guidance assistance. 




Recent Post:


Quick Enquiry

Please wait while submission in progress...


Contact Us

Chennai

  93450 45466

Bangalore

 93450 45466

Coimbatore

 95978 88270

Online

93450 45466

Madurai

97900 94102

Pondicherry

93635 21112

For Hiring

 93840 47472
 hr@fita.in

Corporate Training

 90036 23340


Read More Read less

FITA Academy Branches

Chennai

Bangalore

Coimbatore

Other Locations

FITA Academy - Velachery
Plot No 7, 2nd floor,
Vadivelan Nagar,
Velachery Main Road,
Velachery, Chennai - 600042
Tamil Nadu

    :   93450 45466

FITA Academy - Anna Nagar
No 14, Block No, 338, 2nd Ave,
Anna Nagar,
Chennai 600 040, Tamil Nadu
Next to Santhosh Super Market

    :   93450 45466

FITA Academy - T Nagar
05, 5th Floor, Challa Mall,
T Nagar,
Chennai 600 017, Tamil Nadu
Opposite to Pondy Bazaar Globus

    :   93450 45466

FITA Academy - Tambaram
Nehru Nagar, Kadaperi,
GST Road, West Tambaram,
Chennai 600 045, Tamil Nadu
Opposite to Saravana Jewellers Near MEPZ

    :   93450 45466

FITA Academy - Thoraipakkam
5/350, Old Mahabalipuram Road,
Okkiyam Thoraipakkam,
Chennai 600 097, Tamil Nadu
Next to Cognizant Thoraipakkam Office and Opposite to Nilgris Supermarket

    :   93450 45466

FITA Academy - Porur
17, Trunk Rd,
Porur
Chennai 600116, Tamil Nadu
Above Maharashtra Bank

    :   93450 45466

FITA Academy Marathahalli
No 7, J J Complex,
ITPB Road, Aswath Nagar,
Marathahalli Post,
Bengaluru 560037

    :   93450 45466

FITA Academy - Saravanampatty
First Floor, Promenade Tower,
171/2A, Sathy Road, Saravanampatty,
Coimbatore - 641035
Tamil Nadu

    :   95978 88270

FITA Academy - Singanallur
348/1, Kamaraj Road,
Varadharajapuram, Singanallur,
Coimbatore - 641015
Tamil Nadu

    :   95978 88270

FITA Academy - Madurai
No.2A, Sivanandha salai,
Arapalayam Cross Road,
Ponnagaram Colony,
Madurai - 625016, Tamil Nadu

    :   97900 94102

FITA Academy - Pondicherry
410, Villianur Main Rd,
Sithananda Nagar, Nellitope,
Puducherry - 605005
Near IG Square

    :   93635 21112

Read More Read less
  • Are You Located in Any of these Areas

    Adyar, Adambakkam, Anna Salai, Ambattur, Ashok Nagar, Aminjikarai, Anna Nagar, Besant Nagar, Chromepet, Choolaimedu, Guindy, Egmore, K.K. Nagar, Kodambakkam, Koyambedu, Ekkattuthangal, Kilpauk, Meenambakkam, Medavakkam, Nandanam, Nungambakkam, Madipakkam, Teynampet, Nanganallur, Navalur, Mylapore, Pallavaram, Purasaiwakkam, OMR, Porur, Pallikaranai, Poonamallee, Perambur, Saidapet, Siruseri, St.Thomas Mount, Perungudi, T.Nagar, Sholinganallur, Triplicane, Thoraipakkam, Tambaram, Vadapalani, Valasaravakkam, Villivakkam, Thiruvanmiyur, West Mambalam, Velachery and Virugambakkam.

    FITA Velachery or T Nagar or Thoraipakkam OMR or Anna Nagar or Tambaram or Porur branch is just few kilometre away from your location. If you need the best training in Chennai, driving a couple of extra kilometres is worth it!