Basics of Class Inheritance in Python

09/11/2021

Contents

In this article, you will learn about basics of class inheritance in Python.

Basics of Class Inheritance in Python

Class inheritance is a fundamental concept in object-oriented programming that allows one class to inherit attributes and methods from another class. In Python, you can define a new class that is based on an existing class by using the syntax:

class ChildClassName(ParentClassName):
    # class definition

This creates a subclass, or child class, called ChildClassName that inherits all the attributes and methods from the ParentClassName. The ChildClassName can then add new attributes and methods, or override existing ones.

Here’s an example:

class Animal:
    def __init__(self, name):
        self.name = name
    
    def speak(self):
        print("I am an animal.")
    
class Dog(Animal):
    def __init__(self, name):
        super().__init__(name)
    
    def speak(self):
        print("Woof!")

In this example, we have a parent class Animal with an __init__ method and a speak method, and a child class Dog that inherits from Animal. Dog has its own __init__ method that calls the parent class’s __init__ method using the super() function. Dog also has its own speak method that overrides the parent class’s speak method.

To create an instance of the Dog class, we can use the following code:

my_dog = Dog("Rufus")
print(my_dog.name)   # Output: Rufus
my_dog.speak()       # Output: Woof!

This code creates a new Dog object with the name “Rufus” and calls the speak method, which prints “Woof!”. Since the Dog class inherits from the Animal class, it also has access to the name attribute and the speak method from the parent class.