SyntaxStudy
Sign Up
Python Beginner 8 min read

Single Inheritance

Single Inheritance

Inheritance lets a child class reuse and extend the behavior of a parent class. Use super() to call parent methods.

Basic Syntax

class Animal:
    def __init__(self, name, sound):
        self.name  = name
        self.sound = sound

    def speak(self):
        return f"{self.name} says {self.sound}!"

    def describe(self):
        return f"I am {self.name}"

Child Class

class Dog(Animal):
    def __init__(self, name, breed):
        super().__init__(name, "Woof")  # call parent __init__
        self.breed = breed

    def fetch(self):
        return f"{self.name} fetches the ball!"

class Cat(Animal):
    def __init__(self, name, indoor=True):
        super().__init__(name, "Meow")
        self.indoor = indoor

Using the Classes

dog = Dog("Rex", "German Shepherd")
cat = Cat("Whiskers")

print(dog.speak())      # Rex says Woof!  (inherited)
print(dog.fetch())      # Rex fetches the ball!
print(cat.describe())   # I am Whiskers  (inherited)

print(isinstance(dog, Dog))    # True
print(isinstance(dog, Animal)) # True
print(issubclass(Dog, Animal)) # True
Example
class Vehicle:
    def __init__(self, make, model, year):
        self.make  = make
        self.model = model
        self.year  = year

    def info(self):
        return f"{self.year} {self.make} {self.model}"

class ElectricCar(Vehicle):
    def __init__(self, make, model, year, range_km):
        super().__init__(make, model, year)
        self.range_km = range_km

    def info(self):
        return f"{super().info()} (Electric, {self.range_km}km range)"

ec = ElectricCar("Tesla", "Model 3", 2024, 570)
print(ec.info())
print(isinstance(ec, Vehicle))  # True
Pro Tip

Always call super().__init__() in the child's __init__ to ensure the parent initializes its attributes properly.