169. Polymorphism in Python

Snippet 1: Basic Polymorphism with Method Overriding

class Animal:
    def sound(self):
        return "Some sound"

class Dog(Animal):
    def sound(self):
        return "Bark"

class Cat(Animal):
    def sound(self):
        return "Meow"

animals = [Dog(), Cat()]
for animal in animals:
    print(animal.sound())

Snippet 2: Polymorphism with Function Arguments

class Rectangle:
    def area(self, length, width):
        return length * width

class Circle:
    def area(self, radius, _=None):
        return 3.14 * radius * radius

def print_area(shape, *args):
    print("Area:", shape.area(*args))

print_area(Rectangle(), 5, 10)
print_area(Circle(), 7)

Snippet 3: Polymorphism in Operator Overloading


Snippet 4: Polymorphism with Abstract Base Classes


Snippet 5: Polymorphism with Dynamic Dispatch


Snippet 6: Polymorphism in Class Methods


Snippet 7: Polymorphism in Built-In Functions


Snippet 8: Polymorphism with Duck Typing


Snippet 9: Polymorphism with Inheritance and Super


Snippet 10: Polymorphism in Nested Classes


Last updated