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()
- We have a base class
Animalthat represents a generic animal with a
nameattribute and a
- We define a derived class
Dogthat inherits from the
Dogclass adds a
breedattribute and overrides the
speak()method with a specialized implementation.
- We create objects of both classes,
- We access the attributes (
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:
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
Once you’ve completed the task, you can proceed to the next lesson.