Programmation Orientée Objet en Python
  • Back to Main Website
  • Home
  • Introduction: Histoire et Concepts
    • Introduction: Histoire et Concepts
    • Histoire de la programmation
    • Première Structuration des données
    • Naissance de la POO
    • Python: tout n’est qu’objet
    • Python : Simplicité des objets et performance sous-jacente
    • Classes en Python : Concepts fondamentaux

    • Travaux Pratiques
    • Construire sa propre Liste
    • Construire son propre DataFrame
  • Encapsulation, Héritage, Composition et Dunder
    • Encapsulation, Heritage, Composition et Dunder
    • Encapsulation en Python
    • Héritage en Python : Concept et intérêt
    • Héritage vs Composition
    • Méthodes Dunder en Python
    • Python call Method: A Fun Exploration

    • Travaux Pratiques
    • TP: Heritage avec le pricing d’option
    • TP : Ajouter des méthodes dunder à DataFrameSimple
    • TP : Étendre la classe Liste avec des méthodes dunder
    • TP: Dunder Method with Tensor for Automatic Differentiation
  • Polymorphisme et Surcharge
    • Polymorphisme et Surcharge
    • Polymorphism in Object-Oriented Programming
    • Polymorphism in Python: Function Overloading and Type Checking
    • Class Creation: Standard vs type()
    • Type Hinting, Typing Module, and Linters in Python
    • Abstract Classes
    • Protocol Classes

    • Travaux Pratiques
    • TP
  • Decorators
    • Design Patterns
    • The decorator pattern
    • Decorator Practically
    • Built-in Decorators and Standard Library Decorators in Python
    • Practical Decorators in Python Libraries

    • Travaux Pratiques
    • TP: Monte Carlo Option Pricing with Decorators
    • TP: Optimizing Heston Model Monte Carlo Simulation
  • Project Management and Packaging
    • Project and Package
    • Organizing Python Projects
    • Understanding imports
    • Python Package Management and Virtual Environments
    • Unit Testing in Python

    • Travaux Pratiques
    • TP: Creating a Linear Regression Package
  • Design Patterns
    • OOP Design Patterns
    • Python-Specific Design Patterns
    • Creation Design Patterns
    • Structural Design Patterns
    • Behavioral Design Pattern

    • Travaux Pratiques
    • TP
  • Sujets de Projets possibles
    • Projets
    • Projets POO - 2024-2025
  • Code source
  1. Polymorphism in Object-Oriented Programming
  • Polymorphisme et Surcharge
  • Polymorphism in Object-Oriented Programming
  • Polymorphism in Python: Function Overloading and Type Checking
  • Class Creation: Standard vs type()
  • Type Hinting, Typing Module, and Linters in Python
  • Abstract Classes
  • Protocol Classes
  • Travaux Pratiques
    • TP

On this page

  • Polymorphism in Object-Oriented Programming
    • General Concept
      • Key Aspects of Polymorphism:
      • Types of Polymorphism:
      • Example of Polymorphism:
    • Method Overriding
      • Key Points about Method Overriding:
      • Example of Method Overriding:
      • Benefits of Method Overriding:

Polymorphism in Object-Oriented Programming

Cours
Fondamentaux
Learn about polymorphism in object-oriented programming (OOP), including method overriding, runtime polymorphism, and how it enables flexible and extensible code structures.
Author

Remi Genet

Published

2024-10-21

Pyodide Status

Initializing Python Packages

Polymorphism in Object-Oriented Programming


General Concept

Polymorphism is a fundamental principle in object-oriented programming (OOP) that allows objects of different types to be treated as objects of a common base type. The word “polymorphism” comes from Greek, meaning “many forms.” In OOP, it refers to the ability of a single interface to represent different underlying forms (data types or classes).

Key Aspects of Polymorphism:

  1. Same Interface, Different Implementations: Polymorphism allows different classes to have methods with the same name, but with different implementations.

  2. Flexibility: It provides a way to use a class exactly like its parent, but with its own specific implementation.

  3. Simplification: It simplifies programming interfaces, making code more modular and extensible.

  4. Runtime Decision: The specific method that gets called is often determined at runtime, based on the actual type of the object.

Types of Polymorphism:

  1. Compile-time Polymorphism (Static):
    • Achieved through method overloading
    • Resolved at compile time
  2. Runtime Polymorphism (Dynamic):
    • Achieved through method overriding
    • Resolved at runtime

Example of Polymorphism:

Consider a base class Animal with a method make_sound(). Different animals can implement this method differently:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Animal:
    def make_sound(self):
        pass
class Dog(Animal):
    def make_sound(self):
        return "Woof!"
class Cat(Animal):
    def make_sound(self):
        return "Meow!"
class Cow(Animal):
    def make_sound(self):
        return "Moo!"
# Using polymorphism
animals = [Dog(), Cat(), Cow()]
for animal in animals:
    print(animal.make_sound())

In this example, each animal class implements the make_sound() method differently, but they can all be treated as Animal objects.

Method Overriding

Method overriding is a fundamental aspect of runtime polymorphism. It occurs when a derived class (child class) has a method with the same name and signature as a method in its base class (parent class).

Key Points about Method Overriding:

  1. Same Name and Signature: The overriding method must have the same name and parameter list as the method in the parent class.

  2. Runtime Decision: The method to be invoked is determined at runtime based on the object’s type.

  3. Extends or Modifies Behavior: Overriding allows a child class to provide a specific implementation of a method that is already defined in its parent class.

  4. Polymorphic Behavior: It’s a key mechanism for achieving polymorphic behavior in OOP.

Example of Method Overriding:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Shape:
    def area(self):
        return 0
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 ** 2
# Using method overriding
shapes = [Rectangle(5, 3), Circle(4), Shape()]
for shape in shapes:
    print(f"Area: {shape.area()}")

In this example: - The Shape class provides a default implementation of area(). - Rectangle and Circle override this method with their specific implementations. - We can treat all objects as Shape instances, but each will use its own area() method.

Benefits of Method Overriding:

  1. Customization: Allows subclasses to provide specific implementations of methods.
  2. Code Reusability: Reuses the method name from the parent class, maintaining a logical hierarchy.
  3. Runtime Flexibility: Enables objects to behave differently based on their actual class, while still using a common interface.

Method overriding is a powerful feature that, when used correctly, can lead to more flexible and maintainable code structures in object-oriented programming.

Back to top
Polymorphisme et Surcharge
Polymorphism in Python: Function Overloading and Type Checking

Programmation Orienté Object en Python, Rémi Genet.
Licence
Code source disponible sur Github

 

Site construit avec et Quarto
Inspiration pour la mise en forme du site ici
Code source disponible sur GitHub