
Python Classes and Objects Part-4
What is polymorphism?
It means we can use same method name in different classes , but each class can do it in its own way.
for example:
class Dog:
def sound(self):
print("Woof")
class Cat:
def sound(self):
print("Meow")
class Cow:
def sound(self):
print("Moo")
animals = [Dog(), Cat(), Cow()]
for a in animals:
a.sound()Output:
Woof
Meow
MooHere, all three classes have a method called sound(), but each one does something different. That is polymorphism.
Why do we need polymorphism?
Because we can write one common piece of code (like the for loop above) that works for many different types of objects, without writing separate code for each one.
What is abstraction?
Abstraction is used to hide complex data which is more like a personal data and it only shows necessary data which user needs.
for example, think about a car. We use the steering wheel and pedals, we don't need to know how the engine works inside. That is abstraction.
How do we do abstraction in Python?
We use something called an abstract class. It tells other classes "you must have this method", without saying how it should work.
for example:
class Shape(ABC):
@abstractmethod
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 * self.radius
shapes = [Rectangle(4, 5), Circle(3)]
for s in shapes:
print("Area:", s.area())Output:
Area: 20
Area: 28.26Here, Shape is an abstract class. It just says "every shape must have area()". Rectangle and Circle each write their own version of area().
What happens if we don't write the required method?
Python will not allow us to create the object.
for example:
class Triangle(Shape):
def __init__(self, base, height):
self.base = base
self.height = height
# forgot to add area()
t1 = Triangle(3, 4) # this gives an errorSince Triangle did not write area(), Python stops us from creating the object.
Join Techsnap Creators
Share your knowledge and earn ??
Want to showcase your tech expertise and get rewarded for your insights? Join the Techsnap creator network!
Write insightful blogs, stay ahead of industry trends, and grow your professional brand while helping others in the community.
Ready to make an impact?

Comments