Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Understanding Inheritance and Polymorphism for Python Object-Oriented Programming

Tech 3

Single inheritance occurs when a subclass extends exactly one parent class. Multiple inheritance refers to a subclass deriving attributes and behaviors from two or more separate parent classes. Inheritance streamlines application development and maintenance by enabling code reuse and supporting the creation of hierarchical class structures.

Polymorphism is a core object-oriented programming concept where objects belonging to different classes can respond to the same method call with distinct, class-specific behaviors. This lets developers interact with objects through a unified interface without needing to account for their underlying type. Python implements polymorphism implicitly as a dynamically typed language: no explicit type declarations are required, and any object that implements the called method will run its implementation when invoked, regardless of its class.

Single Inheritance

Single inheritance limits a subclass to one direct parent class. Subclasses inherit all public attributes and methods from the parent, can extend the parent with new properties and behaviors, or override inherited methods to modify their behavier.

Single Inheritance Example

class Wildlife:
    def __init__(self, species_label):
        self.species_label = species_label

    def make_sound(self):
        raise NotImplementedError("All subclasses must implement this method")


class Canine(Wildlife):
    def make_sound(self):
        return f"{self.species_label} emits a loud bark!"


class Feline(Wildlife):
    def make_sound(self):
        return f"{self.species_label} produces a soft meow!"


golden_retriever = Canine("Golden Retriever")
siamese_cat = Feline("Siamese Cat")

print(golden_retriever.make_sound())
print(siamese_cat.make_sound())

In this example, Canine and Feline both inherit from the Wildlife parent class. Each subclass implements the required make_sound method with logic specific to their animal type, demonstrating core single inheritance functionality.

Multiple Inheritance

Multiple inheritance allows a subclass to inherit from multiple independent parent classes, combining capabilities from all sources. This pattern requires careful design to avoid overly complex inheritance chains and unintended naming conflicts between parent class methods.

Multiple Inheritance Example

class BackendDeveloper:
    def __init__(self):
        print("Initializing backend developer skill set")

    def core_skill(self):
        print("Proficient in server-side programming and database management")

    def write_api(self):
        print("Able to build RESTful APIs for data exchange")


class UxDesigner:
    def __init__(self):
        print("Initializing UX designer skill set")

    def core_skill(self):
        print("Skilled in user research and intuitive interface design")

    def create_mockup(self):
        print("Capable of building high-fidelity product mockups")


class FullStackDesigner(BackendDeveloper, UxDesigner):
    def __init__(self):
        super().__init__()

    def show_base_skill(self):
        super().core_skill()


cross_role_worker = FullStackDesigner()
cross_role_worker.show_base_skill()
cross_role_worker.create_mockup()
cross_role_worker.write_api()

The FullStackDesigner subclass inherits from both BackendDeveloper and UxDesigner parenet classes. The super().__init__ call only executes the constructor of the first listed parent class, following Python's Method Resolution Order (MRO). The core_skill call also resolves to the first matching implementation from BackendDeveloper per MRO rules. You can view the full resolution order for any class by calling its mro() class method. Python uses the C3 linearization algorithm to calculate MRO, ensuring each parent class appears before its subclasses and each class is processed exactly once per resolution chain.

Single inheritance has a straightforward, easy-to-follow hierarchy with minimal risk of naming conflicts, but is less flexible for combining disjoint sets of functionality. Multiple inheritance enables more modular, reusable designs by combining capabilities from multiple sources, but can lead to complicated, hard-to-debug structures if not carefully planned, especially when overlapping method names exist across parent classes. Clear inheritance boundaries and minimal overlapping method signatures help mitigate the complexity of multiple inheritance implementations.

Parent Class Method Overriding

In object-oriented programming, subclasses often need to adjust the behavior of methods inherited from parent classes. This is achieved via method overriding, where a subclass defines a method with the exact same name and call signature as a parent class method. When the method is invoked on a subclass instance, the subclass implementation runs instead of the inherited parent version.

class Transportation:
    def __init__(self, model_id):
        self.model_id = model_id

    def activate_alert(self):
        return "Generic alert sound activated for transportation device"


class ElectricScooter(Transportation):
    def __init__(self, model_id, manufacturer):
        super().__init__(model_id)
        self.manufacturer = manufacturer

    def activate_alert(self):
        return f"Loud beep activated for {self.manufacturer} electric scooter model {self.model_id}"


generic_transport = Transportation("GEN-001")
print(generic_transport.activate_alert())

my_scooter = ElectricScooter("SCOOT-123", "Segway")
print(my_scooter.activate_alert())

You can explicitly call the parent class version of an overridden method at any point using super().method_name() if you need to retain or extend the original parent functionality.

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.