Andromeda
Note

Inheritance (Python)

Definition

A feature of Object-Oriented Programming where a new class (the Child Class or subclass) takes on the attributes and methods of an existing class (the Parent Class or superclass).

Why It Matters

Software is often too complex to hold in a single human mind. Inheritance provides a way to organize that complexity into a logical hierarchy, ensuring that common features (like “moving”) only have to be written once and can be shared by many different objects (like “cars,” “dogs,” and “planes”). It is the primary tool for creating “DRY” (Don’t Repeat Yourself) code that is easy to maintain and scale.

Core Concepts

class Animal:
    def speak(self):
        print("Animal sound")

class Dog(Animal):
    def speak(self):
        print("Woof!")  # Overriding

my_dog = Dog()
my_dog.speak()  # "Woof!"
  • Parent vs. Child: The child class “is a” specialized version of the parent class.
  • super() Function: Used to call methods from the parent class, typically to initialize parent attributes in the child’s __init__.
  • Method Overriding: Redefining a parent’s method in the child class to change its behavior for that specific subclass.
  • Composition (Instances as Attributes): Instead of inheriting, a complex class can include an instance of a simpler class as an attribute (e.g., an ElectricCar having a Battery instance).

Connected Concepts