Understanding Inheritance in Python - How does inheritance work in Python?

How does inheritance work in Python?

Inheritance is a fundamental concept in object-oriented programming (OOP) that allows a new class to be created based on an existing class. This new class is called a derived class, and the existing class is called the base class.

In Python, inheritance is implemented using the class keyword. A derived class is defined by specifying the base class in parentheses after the class name. For example:

class DerivedClassName(BaseClassName):
    # properties and methods

The derived class inherits all the attributes and methods of the base class, and can also add its own attributes and methods. This allows for code reuse and organization.

For example, let's say we have a base class called Animal with an attribute name and a method speak(). We can create a derived class called Dogs that inherits the name attribute and speak() method from the Animals class, but also adds a new attribute breed and method bark().

class Animals:
    def __init__(self, name):
        self.name = name
        
    def speak(self):
        pass
    
class Dogs(Animals):
    def __init__(self, name, breed):
        super().__init__(name)
        self.breed = breed
        
    def bark(self):
        print("Woof!")
 

In the above example, we use the super() function to call the __init__ method of the base class. This allows the Dogs class to initialize its name attribute by passing the name argument to the Animals class's __init__ method.

Python also allows for multiple inheritance, where a class can inherit from multiple base classes. This is done by specifying multiple base classes in the parentheses after the class name, separated by commas. For example:

class DerivedClass(BaseClass1, BaseClass2):
    # properties and methods

In conclusion, Inheritance is a powerful feature in Python that allows for code reuse and organization by creating new classes based on existing classes. It allows the derived class to inherit the attributes and methods of the base class and also add its own attributes and methods. This feature also allows multiple inheritance which means a class can inherit from multiple base classes.