Single Inheritance

Inheriting from one parent class

Interview Relevant: Basic inheritance

Single Inheritance

Inherit from a single parent class.

Code Examples

Basic single inheritance.

python
1class Animal:
2    def __init__(self, name):
3        self.name = name
4
5    def speak(self):
6        pass
7
8class Dog(Animal):  # Inherit from Animal
9    def speak(self):
10        return f"{self.name} says Woof!"
11
12class Cat(Animal):
13    def speak(self):
14        return f"{self.name} says Meow!"
15
16dog = Dog("Buddy")
17cat = Cat("Whiskers")
18print(dog.speak())  # Buddy says Woof!
19print(cat.speak())  # Whiskers says Meow!
20
21# Check inheritance
22isinstance(dog, Dog)     # True
23isinstance(dog, Animal)  # True
24issubclass(Dog, Animal)  # True

AI Tutor

Ask about the topic

Sign in Required

Please sign in to use the AI tutor

Sign In