Hi there, we’re Harisystems
"Unlock your potential and soar to new heights with our exclusive online courses! Ignite your passion, acquire valuable skills, and embrace limitless possibilities. Don't miss out on our limited-time sale - invest in yourself today and embark on a journey of personal and professional growth. Enroll now and shape your future with knowledge that lasts a lifetime!".
For corporate trainings, projects, and real world experience reach us. We believe that education should be accessible to all, regardless of geographical location or background.
1Python Polymorphism
Polymorphism is a key concept in object-oriented programming (OOP) that allows objects of different classes to be treated as interchangeable. It promotes code flexibility and reusability by enabling the use of a common interface across different types of objects. In this article, we'll explore the concept of polymorphism in Python and provide examples to help you understand its implementation and benefits.
Example 1: Polymorphic Behavior
Let's start with a basic example that demonstrates polymorphic behavior:
class Shape:
def draw(self):
raise NotImplementedError("Subclass must implement this method.")
class Circle(Shape):
def draw(self):
print("Drawing a circle.")
class Square(Shape):
def draw(self):
print("Drawing a square.")
shapes = [Circle(), Square()]
for shape in shapes:
shape.draw()
In this code, we define an abstract base class called "Shape" that has a "draw" method. The "draw" method raises a NotImplementedError to ensure that subclasses implement their own "draw" method. We create two subclasses, "Circle" and "Square", that inherit from the Shape class and provide their own implementation of the "draw" method. We then create a list called "shapes" that contains instances of both Circle and Square. By iterating over the shapes and calling the "draw" method, we achieve polymorphic behavior, as the specific implementation of "draw" is determined at runtime based on the type of object.
Example 2: Polymorphic Functions
Polymorphism can also be achieved through functions that accept objects of different types. Here's an example:
class Dog:
def speak(self):
print("Woof!")
class Cat:
def speak(self):
print("Meow!")
def make_sound(animal):
animal.speak()
dog = Dog()
cat = Cat()
make_sound(dog) # Output: Woof!
make_sound(cat) # Output: Meow!
In this code, we define two classes, Dog and Cat, each with a "speak" method. We also define a function called "make_sound" that accepts an object of any type that has a "speak" method. Inside the function, we call the "speak" method on the object, achieving polymorphic behavior. We create instances of Dog and Cat and pass them to the "make_sound" function, resulting in different sounds being produced based on the type of object.
Example 3: Polymorphic Interfaces
Polymorphism can be achieved through interfaces, which define a set of methods that a class must implement. Here's an example:
class Printable:
def print(self):
raise NotImplementedError("Subclass must implement this method.")
class Document(Printable):
def print(self):
print("Printing a document.")
class Image(Printable):
def print(self):
print("Printing an image.")
def print_object(obj):
obj.print()
document = Document()
image = Image()
print_object(document) # Output: Printing a document.
print_object(image) # Output: Printing an image.
In this code , we define an interface called "Printable" that specifies a "print" method. We create two classes, Document and Image, that inherit from the Printable interface and implement their own "print" method. We then define a function called "print_object" that accepts an object of any type that implements the Printable interface. Inside the function, we call the "print" method on the object, achieving polymorphic behavior. We create instances of Document and Image and pass them to the "print_object" function, resulting in different printing actions based on the type of object.
Conclusion
Polymorphism is a powerful feature in Python that allows objects of different types to be used interchangeably. By understanding and leveraging polymorphism, you can write more flexible and reusable code. Experiment with the examples provided and explore the possibilities of polymorphism in your Python projects.
4.5L
Learners
20+
Instructors
50+
Courses
6.0L
Course enrollments
Future Trending Courses
When selecting, a course, Here are a few areas that are expected to be in demand in the future:.
Future Learning for all
If you’re passionate and ready to dive in, we’d love to join 1:1 classes for you. We’re committed to support our learners and professionals their development and well-being.
View CoursesMost Popular Course topics
These are the most popular course topics among Software Courses for learners