Python Inheritance Foundation
parent / child OOP 02 Foundation

Child classes inherit from parent classes

Reuse code and behavior from a parent class by creating child classes that extend it with more specific functionality.

Picture this: child gets parent tools

The child class reuses the parent, then adds or overrides.

Parentbase class
→
Child(Parent)inherits
→
extra methodsonly child

What is inheritance?

Inheritance lets a child class acquire properties and methods from a parent class. The child can add its own new properties and methods, or override parent methods.

UML Inheritance Diagram

classDiagram
    class Animal {
      +sleep()
      +eat()
      +sound()
    }
    class Dog {
      +bark()
      +sound()
    }
    class Cat {
      +sound()
    }
    Animal <|-- Dog
    Animal <|-- Cat
            
Dog and Cat inherit from Animal. They share methods, but can override them.

Inheritance Structure

Animal Dog Cat
Both Dog and Cat extend Animal, forming a hierarchy.

Real-world analogy

A parent class "Animal" has sleep(), eat(), and sound(). A child class "Dog" inherits these but overrides sound() to bark. A child class "Cat" overrides sound() to meow. Code reuse at its best!

Parent (Base) Class

  • Defines common behavior
  • Shared across all children
  • General, reusable code

Child (Derived) Class

  • Inherits from parent
  • Can add new methods
  • Can override parent methods

Inheritance syntax

1class Animal: # Parent
2def sleep(self):
3print("Zzz...")
4class Dog(Animal): # Child
5def bark(self):
6print("Woof!")

Child inherits from parent

Press "Run one step" to see inheritance flow

Example Program

1dog = Dog()
2dog.sleep() # Inherited from Animal
3dog.bark() # Own method