Inheritance is a fundamental concept in object-oriented programming that allows us to create new classes based on existing classes. The new class, known as the derived class or subclass, inherits the attributes and methods of the existing class, known as the base class or superclass. This promotes code reuse and enables the creation of specialized classes that extend or modify the behavior of the base class.

Let’s explore how to use inheritance in Python:

# Base class
class Animal:
    def __init__(self, name):
        self.name = name

    def speak(self):
        print("The animal speaks.")

# Derived class
class Dog(Animal):
    def __init__(self, name, breed):
        super().__init__(name)
        self.breed = breed

    def speak(self):
        print("Woof! Woof!")

# Creating objects
animal = Animal("Generic Animal")
dog = Dog("Buddy", "Labrador")

# Accessing attributes
print("Animal:", animal.name)
print("Dog:", dog.name, dog.breed)

# Calling methods
animal.speak()
dog.speak()

Explanation:

  • We have a base class Animal that represents a generic animal with a name attribute and a speak() method.
  • We define a derived class Dog that inherits from the Animal class. The Dog class adds a breed attribute and overrides the speak() method with a specialized implementation.
  • We create objects of both classes, animal and dog.
  • We access the attributes (name and breed) using dot notation.
  • We call the methods (speak()) on the objects, which will invoke the appropriate method based on the object’s class.

Now it’s time for a practical task:

Task 12:

Create a class called Square that represents a square object. The Square class should inherit from a Rectangle class (from the previous lesson) and add a method called is_square() that checks if the rectangle is actually a square by comparing its width and height. Create a square object and test the calculate_area(), calculate_perimeter(), and is_square() methods.

Once you’ve completed the task, you can proceed to the next lesson.