What is Inheritance in Python: Simple Explanation and Example
inheritance is a way for one class to get properties and behaviors from another class. It lets you create a new class based on an existing one, so you can reuse code and build relationships between classes.How It Works
Inheritance in Python works like a family tree. Imagine you have a parent class that has some traits or actions. A child class can inherit these traits and actions without rewriting them. This saves time and keeps your code clean.
Think of it like a blueprint: the parent class is the original blueprint, and the child class is a new blueprint that copies the original but can also add or change things. This way, you can build complex programs by reusing simple parts.
Example
This example shows a parent class Animal and a child class Dog that inherits from it. The Dog class can use the sound method from Animal and also has its own method.
class Animal: def sound(self): return "Some sound" class Dog(Animal): def sound(self): return "Bark" def fetch(self): return "Fetching the ball" my_dog = Dog() print(my_dog.sound()) print(my_dog.fetch())
When to Use
Use inheritance when you want to create new classes that share common features with existing classes. It helps avoid repeating code and makes your program easier to maintain.
For example, in a game, you might have a general Character class and then create specific classes like Wizard or Warrior that inherit from it but add their own special abilities.
Key Points
- Inheritance allows a class to reuse code from another class.
- The child class can add or change features from the parent class.
- It helps organize code and reduce repetition.
- Python uses parentheses to show inheritance, like
class Child(Parent):.