8 3-Polymorphism
8 3-Polymorphism
ipynb - Colab
Polymorphism
Polymorphism is a core concept in Object-Oriented Programming (OOP) that allows objects of different classes to be treated as objects of a
common superclass. It provides a way to perform a single action in different forms. Polymorphism is typically achieved through method
overriding and interfaces
## Base Class
class Animal:
def speak(self):
return "Sound of the animal"
## Derived Class 1
class Dog(Animal):
def speak(self):
return "Woof!"
## Derived class
class Cat(Animal):
def speak(self):
return "Meow!"
dog=Dog()
cat=Cat()
print(dog.speak())
print(cat.speak())
animal_speak(dog)
Woof!
Meow!
Woof!
https://colab.research.google.com/drive/1yjMgl56Q-WPfwAQJPihgEUBGNG6j4iXh#printMode=true 1/3
7/18/24, 10:41 AM 8.3-Polymorphism.ipynb - Colab
### Polymorphissm with Functions and MEthods
## base class
class Shape:
def area(self):
return "The area of the figure"
## Derived class 1
class Rectangle(Shape):
def __init__(self,width,height):
self.width=width
self.height=height
def area(self):
return self.width * self.height
##DErived class 2
class Circle(Shape):
def __init__(self,radius):
self.radius=radius
def area(self):
return 3.14*self.radius *self.radius
def print_area(shape):
print(f"the area is {shape.area()}")
rectangle=Rectangle(4,5)
circle=Circle(3)
print_area(rectangle)
print_area(circle)
the area is 20
the area is 28.259999999999998
Abstract Base Classes (ABCs) are used to define common methods for a group of related objects. They can enforce that derived classes
implement particular methods, promoting consistency across different implementations.
https://colab.research.google.com/drive/1yjMgl56Q-WPfwAQJPihgEUBGNG6j4iXh#printMode=true 2/3
7/18/24, 10:41 AM 8.3-Polymorphism.ipynb - Colab
from abc import ABC,abstractmethod
keyboard_arrow_down
Conclusion
## Derived class 1
class Car(Vehicle):
Polymorphism is a powerful feature of OOP that allows for flexibility and integration in code design. It enables a single function to handle
def start_engine(self):
return "Car enginer started"
objects of different classes, each with its own implementation of a method. By understanding and applying polymorphism, you can create more
extensible
## Derived and maintainable
class 2 object-oriented programs.
class Motorcycle(Vehicle):
def start_engine(self):
Start coding or generate with AI.
return "Motorcycle enginer started"
# Function
Start that
coding demonstrates
or generate withpolymorphism
AI.
def start_vehicle(vehicle):
print(vehicle.start_engine())
Start coding or generate with AI.
## create objects of cAr and Motorcycle
Start Car
coding or generate
enginer started with AI.
https://colab.research.google.com/drive/1yjMgl56Q-WPfwAQJPihgEUBGNG6j4iXh#printMode=true 3/3