Python:Python Inheritance, Polymorphism, and the super() Function
Python•Inheritance

Python Inheritance, Polymorphism, and the super() Function

Derived child classes inherit methods and attributes from base classes, overriding them as needed while accessing parent logic via super().

Syntax

class ChildClass(ParentClass): def __init__(self, args): super().__init__(args)

Parameters & Values

Key components and acceptable values for this structure:

ParameterTypeDescription
ParentClassBase ClassClass whose capabilities are inherited.
super()Proxy ObjectDelegates method calls to parent class implementation.

Ready-to-Run Code Example

Executable in Compilra

Run this complete, working example directly without installing Python locally:

# Python Inheritance: Base Employee and Developer Subclass
class Employee:
    def __init__(self, name: str, base_salary: float):
        self.name = name
        self.base_salary = base_salary

    def get_details(self) -> str:
        return f"{self.name} (Base: ${self.base_salary:,.0f})"

class Developer(Employee):
    def __init__(self, name: str, base_salary: float, language: str):
        # Call parent constructor
        super().__init__(name, base_salary)
        self.language = language

    # Method override with polymorphism
    def get_details(self) -> str:
        base_info = super().get_details()
        return f"{base_info} | Lead {self.language} Engineer"

team = [
    Employee("Jane", 75000),
    Developer("Alex", 120000, "Python"),
    Developer("Mark", 115000, "Rust")
]

for member in team:
    print(member.get_details())
Expected Output:
Jane (Base: $75,000)
Alex (Base: $120,000) | Lead Python Engineer
Mark (Base: $115,000) | Lead Rust Engineer

How It Works: Step-by-Step

  • Lines 2-7: Defines parent class Employee with standard name and salary attributes.
  • Lines 9-14: Developer inherits from Employee and uses super().__init__() to invoke parent setup.
  • Lines 17-19: Overrides get_details() method while extending parent functionality.

Key Concepts

  • super() dynamically references the parent class, avoiding hardcoded parent names.
  • Polymorphism allows iterating over parent and child objects with a uniform interface.
  • Python supports multiple inheritance (deriving from multiple classes).

Common Mistake: Forgetting to call super().__init__() in the subclass constructor

Overriding __init__ without super() leaves inherited parent attributes uninitialized.

❌ Incorrect
class Child(Parent):
    def __init__(self, val):
        self.val = val # Parent attributes never set!
✅ Correct
class Child(Parent):
    def __init__(self, name, val):
        super().__init__(name)
        self.val = val

Related Python Tutorials & Compiler

Run and test Python on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

Python Online Compiler