Inheritance and polymorphism are two essential concepts in object-oriented programming, and they play an important role in developing robust, maintainable, and reusable code. In this article, we will discuss these concepts and their implementation in Python.
Inheritance allows us to create a new class that is a modified version of an existing class. The new class inherits the attributes and methods of the existing class but can also add new attributes and methods or override existing ones. In other words, inheritance allows us to reuse existing code and avoid redundancy.
In Python, we can create a subclass by specifying the base class in parentheses after the subclass name. For example, let's say we have a class called Animal
:
class Animal: def __init__(self, name, species): self.name = name self.species = species def make_sound(self): pass
Now, let's create a subclass called Dog
that inherits from Animal
:
class Dog(Animal): def __init__(self, name, breed): super().__init__(name, species="Dog") self.breed = breed def make_sound(self): return "Woof!"
In this example, we override the __init__
method to add the breed
attribute, and we override the make_sound
method to return "Woof!".
Polymorphism, on the other hand, allows us to use a single interface to represent different types of objects. This means that we can have multiple classes that implement the same method but behave differently.
In Python, we can achieve polymorphism through method overriding. For example, let's say we have a class called Shape
:
class Shape: def area(self): pass
Now, let's create two subclasses, Rectangle
and Circle
, that inherit from Shape
and override the area
method:
class Rectangle(Shape): def __init__(self, width, height): self.width = width self.height = height def area(self): return self.width * self.height class Circle(Shape): def __init__(self, radius): self.radius = radius def area(self): return 3.14 * self.radius ** 2
In this example, we have two classes that implement the area
method but behave differently based on their attributes.
To summarize, inheritance and polymorphism are two important concepts in object-oriented programming that allow us to write reusable and maintainable code. In Python, we can create subclasses by specifying the base class in parentheses after the subclass name and achieve polymorphism through method overriding. These concepts are essential for building complex and scalable applications.