0Pricing
Learn AI with Python · Lesson

Polymorphism

Explore how polymorphism enables flexible and dynamic code.

1

Introduction to 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 flexibility and reusability in code.

In this lesson, you’ll learn how to implement polymorphism in Python using methods and classes.

Polymorphism — illustration 1

2

What Is Polymorphism?

Polymorphism allows methods in different classes to share the same name while behaving differently. It makes the code more flexible and easier to extend.

# Defining a superclass
class Animal:
    # Method in the superclass
    def speak(self):
        print("Animal speaks")  # Generic message for all animals

# Defining a subclass that overrides the speak method
class Dog(Animal):
    def speak(self):
        print("Dog barks")  # Specific behavior for Dog

All lessons in this course

  1. Classes and Objects
  2. Attributes and Methods
  3. Inheritance
  4. Polymorphism
  5. Encapsulation and Abstraction
  6. Magic Methods (__str__, __repr__, etc.)
← Back to Learn AI with Python