bytes

tutorials

python

python inheritance and polymorphism

Inheritance and Polymorphism

Module - 7 OOPs in Python
Inheritance and Polymorphism

Overview

Inheritance permits new classes to inherit features from existing classes, decreasing redundancy and reusing code. Polymorphism lets objects of diverse types share the same interface, empowering methods to be executed unexpectedly based on the object type. This decreases the code required and streamlines upkeep.

Definition of Inheritance and Polymorphism

Inheritance: 

Inheritance could be a feature of object-oriented programming that permits one class to acquire characteristics from another class. In other words, inheritance permits a class to be characterized in terms of another class, which makes it simpler to make and keep up an application.

Polymorphism:

Polymorphism allows objects of different types to be treated similarly. In other words, polymorphism allows objects to be treated as a single type of object, even if they are of different types. This means that a single set of code can handle any object, even if the objects are of different types.

Advantages of Inheritance and Polymorphism

Inheritance:

  1. It permits code to be reused and avoids code duplication.
  2. It permits for the creation of hierarchical classifications.
  3. It permits for extensibility, as new subclasses can be made.
  4. It permits for less demanding support and debugging.

Polymorphism:

  1. It permits for the execution of dynamic dispatch and the implementation of interfaces.
  2. It reduces the number of lines of code and makes it simpler to maintain.
  3. It permits for the execution of more generic algorithms.
  4. It permits the execution of more adaptable programs.

Disadvantages of Inheritance and Polymorphism

Inheritance:

  1. Tight coupling: Inheritance makes a firmly coupled relationship among classes, making it troublesome to adjust existing code without breaking other program parts.
  2. Increased complexity: Inheritance can increment the complexity of a program, as increasing classes are included to back the inheritance hierarchy.
  3. Overuse: Inheritance ought to be utilized sparingly because it can lead to overcomplicated designs and implementations that are troublesome to keep up with.

Polymorphism:

  1. Trouble investigating: Polymorphism can make it challenging to investigate code because it can be hard to track the stream of execution when the same code is executing in several ways.
  2. Execution issues: Polymorphism can lead to execution issues, as the framework must check each object's sort to decide which strategy to execute.
  3. Superfluous complexity: Polymorphism can too lead to pointless complexity in the event that it is utilized when a less complex approach would suffice.

Types of Inheritance

  1. Single inheritance: A derived class inherits from one base class.
  2. Multiple inheritance: A derived class inherits from multiple base classes.
  3. Multilevel inheritance: A derived class inherits from a base class that inherits from another base class.
  4. Hierarchical inheritance: Multiple derived classes inherit from the same base class.
  5. Hybrid inheritance: A combination of two or more of the above inheritance types.

Working with Inheritance and Polymorphism in Python

Inheritance in Python refers to the process by which one class can acquire the attributes and methods of another class. This is done by creating an inheritance relationship between the two classes. The class that is doing the inheriting is referred to as the child class, and the class that is being inherited from is referred to as the parent class. Polymorphism in Python is the ability of one object to take on multiple forms. This is done by creating multiple classes inherited from a single base class. Each class can then be used interchangeably, as they all share the same interface. This allows for a great degree of flexibility when it comes to programming. To demonstrate how to work with inheritance and polymorphism in Python, consider the following example of a class hierarchy for a game character.

class Character:
    def **init**(self, health, attack):
        self.health = health
        self.attack = attack
class Wizard(Character):
    def **init**(self, health, attack, magic):
        super().**init**(health, attack)
        self.magic = magic
class Warrior(Character):
    def **init**(self, health, attack, magic):
        super().**init**(health, attack,magic)
        

This code creates a class hierarchy for a game character. It starts with the base class Character, which has two attributes: health and attack. It then creates two child classes, Wizard and Warrior, which both inherit from the Character. The Wizard class adds a new attribute, magic, while the Warrior class does not add any additional attributes. This allows different types of characters to be created using the same interface.

Examples of Inheritance and Polymorphism in Python

class Animal:
    """A generic animal"""
    def __init__(self, name):
        self.name = name

class Dog(Animal):
    """A dog, a sub-class of Animal"""
    def bark(self):
        print("Woof!")

fido = Dog("Fido")
fido.bark() # prints "Woof!"

This code creates a class Animal and a class Dog, which is a sub-class of Animal. The Dog class inherits the init  method from Animal and adds its bark() method. The code then creates an instance of Dog, named Fido, and calls the bark() method on it.

Polymorphism

def print_name(obj):
    print(obj.name)

fido = Dog("Fido")
bob = Cat("Bob")

print_name(fido) # prints "Fido

This code demonstrates polymorphism in Python. The function print_name() takes an object as a parameter and prints out the object's name. The print_name() function can be used with any object with the name attribute, regardless of its class. In this example, it is used with a Dog and a Cat object, both subclasses of Animals.

Limitations of Inheritance and Polymorphism

Inheritance and polymorphism are useful tools for software development and object-oriented programming. However, there are several limitations to be aware of when using inheritance and polymorphism.

  1. Unnecessary complexity: Inheritance and polymorphism can add unnecessary complexity to software design if not used carefully. This can result in software that is difficult to maintain and debug.
  2. Decreased performance: Inheritance and polymorphism can reduce software performance due to the additional overhead associated with their use.
  3. Fragile base class problem: The "Fragile Base Class Problem" occurs when changes to a base class cause unexpected behavior in child classes.
  4. Limited reusability: Inheritance and polymorphism can limit code reusability, as it is often difficult to reuse code based on inheritance or polymorphism.
  5. Lack of flexibility: Inheritance and polymorphism can lack the flexibility necessary for some software designs. For example, if a software design requires the ability to extend the behavior of an object dynamically, then there may be better approaches than inheritance and polymorphism.

Conclusion

Inheritance in object-oriented programming permits one class to inherit characteristics from another, resulting in less demanding code reuse, the creation of hierarchical classifications, and extensibility. Polymorphism empowers distinctive object types to share the same interface, driving the execution of more non-specific algorithms, more adaptable programs, and fewer lines of code. In any case, inheritance can increment program complexity and lead to tight coupling, whereas polymorphism can lead to investigating challenges and execution issues.

Key takeaways

  1. Inheritance permits you to define a class that acquires from another class, giving it access to all the attributes and methods of the parent class. This permits code reuse and helps you make more productive code.
  2. Polymorphism permits you to characterize methods within the parent class that can be overridden within the child class. This allows for a more secluded and flexible codebase because it permits distinctive objects to reply differently to the same method calls.
  3. Both inheritance and polymorphism are effective programming techniques. When utilized legitimately, they can assist you in making more organized, effective, and robust code.
  4. Python gives a number of features that make it simpler to utilize inheritance and polymorphism in your code. These incorporate extraordinary strategies like init() and str(), as well as the utilization of super() to get to the parent class.
  5. Inheritance and polymorphism can be utilized together to form effective and extensible code. Be that as it may, it's imperative to use them appropriately, as they can lead to difficult-to-debug blunders in case not actualized accurately.

Quiz

  1. In object-oriented programming, what is the term for the ability of a class to use the methods and properties of another class? 
    1. Polymorphism 
    2. Inheritance 
    3. Abstraction 
    4. Encapsulation

Answer:b. Inheritance

  1. What is the purpose of polymorphism in object-oriented programming? 
    1. To reduce code duplication 
    2. To abstract away implementation details  
    3. To create objects of different types  
    4. To allow a class to use the methods and properties of another class

Answer:d. To allow a class to use the methods and properties of another class

  1. When a class inherits from another class, what is the term for the class from which the other class inherits?
    1. Subclass 
    2. Base class 
    3. Parent class 
    4. Superclass

Answer:d. Superclass

  1. What is the purpose of overriding a method in object-oriented programming? 
    1. To add additional functionality to a method 
    2. To change the parameters of a method  
    3. To make a method accessible to classes outside of its scope 
    4. To replace the functionality of an existing method

Answer:d. To replace the functionality of an existing method

Related Programs
Full Stack Data Science with Placement Guarantee of 5+ LPA
Course
20,000 people are doing this course
Become a job-ready Data Science professional in 30 weeks. Join the largest tech community in India. Pay only after you get a job above 5 LPA.
Related Tutorials

AlmaBetter’s curriculum is the best curriculum available online. AlmaBetter’s program is engaging, comprehensive, and student-centered. If you are honestly interested in Data Science, you cannot ask for a better platform than AlmaBetter.

avatar
Kamya Malhotra
Statistical Analyst
Fast forward your career in tech with AlmaBetter
Vikash SrivastavaCo-founder & CPTO AlmaBetter
Vikas CTO
Related Tutorials to watch
Top Articles toRead
AlmaBetter
Made with heartin Bengaluru, India
  • Location
  • 4th floor, 133/2, Janardhan Towers, Residency Road, Bengaluru, Karnataka, 560025
  • Follow Us
  • facebookinstagramlinkedintwitteryoutubetelegram

© 2022 AlmaBetter