For Enquiry: 93450 45466

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:

  • Trending Courses

    JAVA Training In Chennai Software Testing Training In Chennai Selenium Training In Chennai Python Training in Chennai Data Science Course In Chennai Digital Marketing Course In Chennai DevOps Training In Chennai German Classes In Chennai Artificial Intelligence Course in Chennai AWS Training in Chennai UI UX Design course in Chennai Tally course in Chennai Full Stack Developer course in Chennai Salesforce Training in Chennai ReactJS Training in Chennai CCNA course in Chennai Ethical Hacking course in Chennai RPA Training In Chennai Cyber Security Course in Chennai IELTS Coaching in Chennai Graphic Design Courses in Chennai Spoken English Classes in Chennai Data Analytics Course in Chennai

    Spring Training in Chennai Struts Training in Chennai Web Designing Course In Chennai Android Training In Chennai AngularJS Training in Chennai Dot Net Training In Chennai C / C++ Training In Chennai Django Training in Chennai PHP Training In Chennai iOS Training In Chennai SEO Training In Chennai Oracle Training In Chennai Cloud Computing Training In Chennai Big Data Hadoop Training In Chennai UNIX Training In Chennai Core Java Training in Chennai Placement Training In Chennai Javascript Training in Chennai Hibernate Training in Chennai HTML5 Training in Chennai Photoshop Classes in Chennai Mobile Testing Training in Chennai QTP Training in Chennai LoadRunner Training in Chennai Drupal Training in Chennai Manual Testing Training in Chennai WordPress Training in Chennai SAS Training in Chennai Clinical SAS Training in Chennai Blue Prism Training in Chennai Machine Learning course in Chennai Microsoft Azure Training in Chennai Selenium with Python Training in Chennai UiPath Training in Chennai Microsoft Dynamics CRM Training in Chennai VMware Training in Chennai R Training in Chennai Automation Anywhere Training in Chennai GST Training in Chennai Spanish Classes in Chennai Japanese Classes in Chennai TOEFL Coaching in Chennai French Classes in Chennai Informatica Training in Chennai Informatica MDM Training in Chennai Big Data Analytics courses in Chennai Hadoop Admin Training in Chennai Blockchain Training in Chennai Ionic Training in Chennai IoT Training in Chennai Xamarin Training In Chennai Node JS Training In Chennai Content Writing Course in Chennai Advanced Excel Training In Chennai Corporate Training in Chennai Embedded Training In Chennai Linux Training In Chennai Oracle DBA Training In Chennai PEGA Training In Chennai Primavera Training In Chennai Tableau Training In Chennai Spark Training In Chennai Appium Training In Chennai Soft Skills Training In Chennai JMeter Training In Chennai Power BI Training In Chennai Social Media Marketing Courses In Chennai Talend Training in Chennai HR Courses in Chennai Google Cloud Training in Chennai SQL Training In Chennai CCNP Training in Chennai PMP Training in Chennai OET Coaching Centre in Chennai Business Analytics Course in Chennai NextJS Course in Chennai Vue JS Course in Chennai

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

    Adambakkam, Adyar, Akkarai, Alandur, Alapakkam, Alwarpet, Alwarthirunagar, Ambattur, Ambattur Industrial Estate, Aminjikarai, Anakaputhur, Anna Nagar, Anna Salai, Arumbakkam, Ashok Nagar, Avadi, Ayanavaram, Besant Nagar, Bharathi Nagar, Camp Road, Cenotaph Road, Central, Chetpet, Chintadripet, Chitlapakkam, Chengalpattu, Choolaimedu, Chromepet, CIT Nagar, ECR, Eechankaranai, Egattur, Egmore, Ekkatuthangal, Gerugambakkam, Gopalapuram, Guduvanchery, Guindy, Injambakkam, Irumbuliyur, Iyyappanthangal, Jafferkhanpet, Jalladianpet, Kanathur, Kanchipuram, Kandhanchavadi, Kandigai, Karapakkam, Kasturbai Nagar, Kattankulathur, Kattupakkam, Kazhipattur, Keelkattalai, Kelambakkam, Kilpauk, KK Nagar, Kodambakkam, Kolapakkam, Kolathur, Kottivakkam, Kotturpuram, Kovalam, Kovilambakkam, Kovilanchery, Koyambedu, Kumananchavadi, Kundrathur, Little Mount, Madambakkam, Madhavaram, Madipakkam, Maduravoyal, Mahabalipuram, Mambakkam, Manapakkam, Mandaveli, Mangadu, Mannivakkam, Maraimalai Nagar, Medavakkam, Meenambakkam, Mogappair, Moolakadai, Moulivakkam, Mount Road, MRC Nagar, Mudichur, Mugalivakkam, Muttukadu, Mylapore, Nandambakkam, Nandanam, Nanganallur, Nanmangalam, Narayanapuram, Navalur, Neelankarai, Nesapakkam, Nolambur, Nungambakkam, OMR, Oragadam, Ottiyambakkam, Padappai, Padi, Padur, Palavakkam, Pallavan Salai, Pallavaram, Pallikaranai, Pammal, Parangimalai, Paruthipattu, Pazhavanthangal, Perambur, Perumbakkam, Perungudi, Polichalur, Pondy Bazaar, Ponmar, Poonamallee, Porur, Pudupakkam, Pudupet, Purasaiwakkam, Puzhuthivakkam, RA Puram, Rajakilpakkam, Ramapuram, Red Hills, Royapettah, Saidapet, Saidapet East, Saligramam, Sanatorium, Santhome, Santhosapuram, Selaiyur, Sembakkam, Semmanjeri, Shenoy Nagar, Sholinganallur, Singaperumal Koil, Siruseri, Sithalapakkam, Srinivasa Nagar, St Thomas Mount, T Nagar, Tambaram, Tambaram East, Taramani, Teynampet, Thalambur, Thirumangalam, Thirumazhisai, Thiruneermalai, Thiruvallur, Thiruvanmiyur, Thiruverkadu, Thiruvottiyur, Thoraipakkam, Thousand Light, Tidel Park, Tiruvallur, Triplicane, TTK Road, Ullagaram, Urapakkam, Uthandi, Vadapalani, Vadapalani East, Valasaravakkam, Vallalar Nagar, Valluvar Kottam, Vanagaram, Vandalur, Vasanta Nagar, Velachery, Vengaivasal, Vepery, Vettuvankeni, Vijaya Nagar, Villivakkam, Virugambakkam, West Mambalam, West Saidapet

    FITA Velachery or T Nagar or Thoraipakkam OMR or Anna Nagar or Tambaram or Porur or Pallikaranai 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!