Python inheritance types with examples: here we are going to explain how inheritance allows you to create new classes (derived classes) that inherit attributes and methods from existing classes (base classes). There are several types of inheritance relationships that can be established between classes. Here are some commonly used types of inheritance in Python, along with examples:
Single Inheritance:
- Single inheritance involves one base class and one derived class.
- The derived class inherits all the attributes and methods from the base class.
class Animal: def speak(self): print("Animal speaks") class Dog(Animal): def bark(self): print("Dog barks") dog = Dog() dog.speak() # Output: Animal speaks dog.bark() # Output: Dog barks
Multiple Inheritance:
- Multiple inheritance involves multiple base classes and one derived class.
- The derived class inherits attributes and methods from all the base classes.
class Flyer: def fly(self): print("Flyer flies") class Swimmer: def swim(self): print("Swimmer swims") class Duck(Flyer, Swimmer): def quack(self): print("Duck quacks") duck = Duck() duck.fly() # Output: Flyer flies duck.swim() # Output: Swimmer swims duck.quack() # Output: Duck quacks
Multilevel Inheritance:
- Multilevel inheritance involves a chain of inheritance, with each derived class being the base class for the next level.
- The derived class inherits attributes and methods from its immediate base class, and so on.
class Animal: def eat(self): print("Animal eats") class Mammal(Animal): def run(self): print("Mammal runs") class Dog(Mammal): def bark(self): print("Dog barks") dog = Dog() dog.eat() # Output: Animal eats dog.run() # Output: Mammal runs dog.bark() # Output: Dog barks
Hierarchical Inheritance:
- Hierarchical inheritance involves multiple derived classes inheriting from a single base class.
- Each derived class inherits attributes and methods from the common base class.
class Animal: def move(self): print("Animal moves") class Dog(Animal): def bark(self): print("Dog barks") class Cat(Animal): def meow(self): print("Cat meows") dog = Dog() dog.move() # Output: Animal moves dog.bark() # Output: Dog barks cat = Cat() cat.move() # Output: Animal moves cat.meow() # Output: Cat meows
These are some of the common types of inheritance relationships in Python. Each type allows you to establish different relationships between classes, enabling code reuse and promoting modularity in your programs.