In this tutorial we want to talk about Python Inheritance and Polymorphism, so we know that Python is an object oriented programming language, and it supports the concepts of inheritance and polymorphism. these concepts allows you to create classes that are more flexible, reusable and maintainable. in this article we want to discuss what is inheritance and polymorphism and how they can be used in Python classes.
Inheritance in Python Classes
Inheritance is a process in which a new class is created by inheriting the properties and methods of an existing class. existing class is called the parent class or base class, and the new class is called child class or derived class. in Python inheritance is done by using super() function and __init__() method.
This is an example of Python Inheritance
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
class Animal: def __init__(self, name): self.name = name def speak(self): raise NotImplementedError("Subclass must implement abstract method") class Dog(Animal): def speak(self): return "Woof" class Cat(Animal): def speak(self): return "Meow" dog = Dog("Fido") cat = Cat("Fluffy") print(dog.speak()) print(cat.speak()) |
In the above example Animal is the parent class, Dog and Cat are child classes. __init__() method is used to initialize the name attribute, which is common to all animals. speak() method is abstract in the Animal class, and is implemented in the Dog and Cat classes. this allows us to create different types of animals that can speak in different ways.
This will be the result
Polymorphism in Python Classes
Polymorphism is the ability of an object to take on multiple forms. in Python polymorphism is done by using of inheritance and method overriding. Method overriding is the process of redefining a method in child class that was already defined in the parent class. this allows child class to change the behavior of the method without changing its name or parameters.
This is polymorphism example in Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
class Shape: def area(self): pass 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 shapes = [Rectangle(3, 4), Circle(5)] for shape in shapes: print(shape.area()) |
In the above example Shape is an abstract class that defines abstract method area. Rectangle and Circle classes are derived from Shape and implement their own versions of the area method. shapes list contains objects of both classes. when we call shape.area() in the loop, and correct version of the area method is called depending on the type of the object.
This will be the result
Subscribe and Get Free Video Courses & Articles in your Email