๐Ÿฑ Polymorphism in Python: Cat Breeds Edition#

๐Ÿš€ Introduction#

Polymorphism is a key concept in object-oriented programming that allows different classes to share the same method names while executing different behaviors based on the object calling them. This makes code more flexible and reusable.

By the end of this guide, you will:

  • Understand the concept of polymorphism and its benefits.

  • Use polymorphism to allow different classes to implement the same methods in unique ways.

  • Implement method overriding to customize behavior in subclasses.

๐Ÿ† What is Polymorphism?#

Polymorphism allows different classes to share the same method names but execute different behaviors depending on the object calling them.

Why is Polymorphism Useful?#

  • Consistency: You can call the same method on different objects without worrying about their exact type.

  • Extensibility: You can add new classes without modifying existing code.

  • Code Reusability: Instead of writing different functions for each type, you use a common interface.

Example: Cat Breeds ๐Ÿฑ#

Different cat breedsโ€”Siamese, Maine Coon, and Bengalโ€”all meow, but each has a unique style of meowing.

This was Prof. Agarโ€™s cat who sadly passed during COVID-19

Class Hierarchy Diagram#

classDiagram
Cat <|-- Siamese
Cat <|-- MaineCoon
Cat <|-- Bengal
class Cat{
+name
+meow()
}
class Siamese{
+meow()
}
class MaineCoon{
+meow()
}
class Bengal{
+meow()
}

๐Ÿพ Creating a Base Cat Class#

class Cat:
    def __init__(self, name):
        self.name = name

    def meow(self):
        """Generic meow sound."""
        return f"{self.name} says: Meow!"

Key Features:#

  • init() initializes the catโ€™s name.

  • meow() is a general method that all cats can override.

๐Ÿ˜ป Creating Specific Cat Breeds with Polymorphism#

Each cat breed overrides the meow() method with its own unique sound.

class Siamese(Cat):
    def meow(self):
        return f"{self.name} says: Meeeeow! (in a fancy Siamese way)"
class MaineCoon(Cat):
    def meow(self):
        return f"{self.name} says: MRRROOOOW! (deep Maine Coon roar)"
class Bengal(Cat):
    def meow(self):
        return f"{self.name} says: Mew! Mew! (quick Bengal chirps)"

Key Features:#

  • Each cat breed overrides meow() differently.

  • The method signature remains the same, but the output varies.

๐ŸŽญ Using Polymorphism in Action#

cats = [Siamese("Luna"), MaineCoon("Thor"), Bengal("Simba")]

for cat in cats:
    print(cat.meow())
Luna says: Meeeeow! (in a fancy Siamese way)
Thor says: MRRROOOOW! (deep Maine Coon roar)
Simba says: Mew! Mew! (quick Bengal chirps)

Output:#

Luna says: Meeeeow! (in a fancy Siamese way)
Thor says: MRRROOOOW! (deep Maine Coon roar)
Simba says: Mew! Mew! (quick Bengal chirps)

Why is this Useful?#

โœ… Same method name (meow) but different behaviors.

โœ… Easier to work with different objects in loops/functions.

โœ… New cat breeds can be added without changing existing code!

๐Ÿ›  More Examples of Polymorphism#

Example 1: Using Polymorphism with a Function#

def make_cats_meow(cat):
    print(cat.meow())


cat1 = Siamese("Luna")
cat2 = MaineCoon("Thor")
cat3 = Bengal("Simba")

make_cats_meow(cat1)  # Luna says: Meeeeow! (in a fancy Siamese way)
make_cats_meow(cat2)  # Thor says: MRRROOOOW! (deep Maine Coon roar)
make_cats_meow(cat3)  # Simba says: Mew! Mew! (quick Bengal chirps)
Luna says: Meeeeow! (in a fancy Siamese way)
Thor says: MRRROOOOW! (deep Maine Coon roar)
Simba says: Mew! Mew! (quick Bengal chirps)
  • A single function make_cats_meow() calls meow() on different cat types without needing if statements.

Example 2: Using Polymorphism with len()#

Pythonโ€™s built-in len() function is an example of polymorphism!

print(len("Paws"))  # Works on a string
print(len([1, 2, 3, 4]))  # Works on a list
print(len({"name": "Whiskers", "age": 3}))  # Works on a dictionary
4
4
2
  • len() works on multiple data types because each object implements len() differently.

๐Ÿ“Œ Key Takeaways#

โœ… Polymorphism allows multiple classes to share method names but have different behaviors.

โœ… Method overriding lets subclasses customize inherited methods.

โœ… Polymorphism makes code more reusable, modular, and scalable.

โœ… Built-in functions like len() also use polymorphism.

๐Ÿฑ Just like every cat has a unique personality, Python classes can override methods to exhibit their own behaviors!