Python Power-Up: OOP Polymorphism - Shape-Shifting Code! 🥷🦎
Issue 16: Discover the Magic of Polymorphism in Python!
Hello Learners,
Welcome back to our Object-Oriented Programming (OOP) adventure! We've learned how to create objects with classes,build family trees with inheritance, and now it's time to make our objects even more adaptable with polymorphism! This concept is like giving your code the power to change its behavior depending on the situation – just like a chameleon changing colors to blend in with its surroundings!
What is Polymorphism?
In simple terms, polymorphism means "many forms." In Python, it means that objects of different classes can be used interchangeably if they share a common interface (i.e., methods with the same name). This allows you to write code that's more flexible and easier to maintain.
Overriding: Customizing Inherited Behaviors
When a child class inherits from a parent class, it can choose to redefine (override) the methods it inherits to provide more specific behavior. Let's see how this works with our animal example:
class Animal:
def speak(self):
print("Generic animal sound")
class Dog(Animal):
def speak(self):
print("Woof!")
class Cat(Animal):
def speak(self):
print("Meow!")
# Create a list of animals
animals = [Dog(), Cat(), Animal()]
# Loop through the animals and make them speak
for animal in animals:
animal.speak()
Output:
Woof!
Meow!
Generic animal sound
Explanation:
We have three classes:
Animal
(the parent class),Dog
, andCat
.Each class has a
speak()
method that is overridden in the child classes.We create a list
animals
containing objects of different types.The loop calls the
speak()
method on each animal, and the appropriate sound is produced, depending on the object's actual class.
Duck Typing: If It Walks Like a Duck...
Python embraces a concept called duck typing, which means it cares more about what an object can do than what type of object it is. If an object has a speak()
method (even if it's not an Animal
), we can still use it as if it were an animal:
class Bird:
def sound(self):
return "Chirp!"
class Car:
def sound(self):
return "Vroom!"
def make_sound(obj):
print(obj.sound())
bird = Bird()
car = Car()
make_sound(bird) # Output: Chirp!
make_sound(car) # Output: Vroom!
Output:
Chirp!
Vroom!
Let's Get Hands-On! Coding Challenges:
Musical Instruments: Create an
Instrument
class with aplay()
method. Then create child classes for different instruments (e.g.,Guitar
,Piano
,Drum
) and override theplay()
method to produce their respective sounds.Shape Shifters: Create a
Shape
class with adraw()
method. Then create child classes likeCircle
,Square
, andTriangle
that override thedraw()
method to display their specific shapes.Transportation: Create a
Vehicle
class with amove()
method. Then create child classes likeCar
,Bicycle
, andAirplane
that overridemove()
to describe how they move.
[Answers at the end of this newsletter]
Poll Time! 🗳️
Stay Tuned!
In the next newsletter, we'll wrap up our OOP series by exploring encapsulation – the art of protecting your code's secrets.
Happy Learning!
Karka Academy
Challenge 1: Musical Instruments
class Instrument:
def play(self):
print("Generic instrument sound")
class Guitar(Instrument):
def play(self):
print("Strumming the guitar: 🎸🎶")
class Piano(Instrument):
def play(self):
print("Playing the piano: 🎹🎵")
class Drum(Instrument):
def play(self):
print("Beating the drums: 🥁🥁🥁")
instruments = [Guitar(), Piano(), Drum()]
for instrument in instruments:
instrument.play()
Output:
Strumming the guitar: 🎸🎶
Playing the piano: 🎹🎵
Beating the drums: 🥁🥁🥁
Challenge 2: Shape Shifters
class Shape:
def draw(self):
print("Drawing a generic shape")
class Circle(Shape):
def draw(self):
print("Drawing a circle: 🔴")
class Square(Shape):
def draw(self):
print("Drawing a square: ⬛")
class Triangle(Shape):
def draw(self):
print("Drawing a triangle: 🔺")
shapes = [Circle(), Square(), Triangle()]
for shape in shapes:
shape.draw()
Output:
Drawing a circle: 🔴
Drawing a square: ⬛
Drawing a triangle: 🔺
Challenge 3: Transportation
class Vehicle:
def move(self):
print("Generic vehicle movement")
class Car(Vehicle):
def move(self):
print("The car is driving on the road.")
class Bicycle(Vehicle):
def move(self):
print("The bicycle is being pedaled.")
class Airplane(Vehicle):
def move(self):
print("The airplane is flying in the sky.")
vehicles = [Car(), Bicycle(), Airplane()]
for vehicle in vehicles:
vehicle.move()
Output:
The car is driving on the road.
The bicycle is being pedaled.
The airplane is flying in the sky.
Key Points:
Polymorphism: Each of these examples demonstrates polymorphism. The same method name (
play()
,draw()
,move()
) is used in different classes, but the behavior is specific to the type of object.Overriding: The child classes override the parent class's methods to provide their own implementations.
Duck Typing: Notice that we don't need to explicitly check the type of object in the
for
loops. Python uses duck typing – if an object has aplay()
,draw()
, ormove()
method, it can be used as if it's a musical instrument, shape,or vehicle, respectively.