Understanding Python Inheritance: A Comprehensive Guide

Understanding Python Inheritance: A Comprehensive Guide

Inheritance in Python allows us to define a class that inherits all the properties and methods from another class. This promotes code reusability and a logical hierarchy in your code structure.

What is Inheritance?

In inheritance, the class that is being inherited from is called the parent class (or base class), while the class that inherits is known as the child class (or derived class).

Creating a Parent Class

Any class can serve as a parent class. Here’s how to create a simple parent class named Animal with properties and methods:

class Animal:
def __init__(self, species, habitat):
self.species = species
self.habitat = habitat
def describe(self):
print(f"This is a {self.species} that lives in {self.habitat}.")

Creating a Child Class

To create a child class that inherits from the parent class, specify the parent class in parentheses:

class Dog(Animal):
pass

The Dog class now has the same properties and methods as the Animal class.

Using the Child Class

Let’s create an object of the Dog class and call its inherited method:

my_dog = Dog("Golden Retriever", "Domestic")
my_dog.describe()

Adding the __init__() Function in the Child Class

To customize the child class, we can add the __init__() function:

class Dog(Animal):
def __init__(self, name, species, habitat):
super().__init__(species, habitat)
self.name = name

Here, we use the super() function to call the parent's __init__() function.

Using the Child Class with Custom Initialization

Now we can create an object of the Dog class:

my_dog = Dog("Buddy", "Labrador", "Domestic")
print(my_dog.name)

Adding Properties to the Child Class

Let’s add a new property called age to the Dog class:

class Dog(Animal):
def __init__(self, name, species, habitat, age):
super().__init__(species, habitat)
self.name = name
self.age = age

Adding Methods to the Child Class

We can also add methods to the child class. For example, let’s add a method bark:

class Dog(Animal):
def bark(self):
print("Woof! Woof!")

Using the New Method

Now let’s create a dog object and call its new method:

my_dog = Dog("Buddy", "Beagle", "Domestic", 3)
my_dog.bark()

Exercise

What is the correct keyword to use inside an empty class to avoid getting an error?

  • empty
  • inherit
  • pass

Conclusion

In this guide, we explored the concept of inheritance in Python. We learned how to create parent and child classes, override methods, and add custom properties and methods. Understanding inheritance is essential for creating efficient and reusable code in Python.