0Pricing
Learn AI with Python · Lección

Polimorfismo

Explore cómo el polimorfismo permite crear código flexible y dinámico.

Polimorfismo es una lección gratuita de Learn AI with Python en CoddyKit. Esta es la lección 4 de 6. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Learn AI with Python, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Learn AI with Python incluye 6 lecciones en total.

Introducción al polimorfismo

Introducción al polimorfismo

El polimorfismo es un concepto fundamental de la Programación Orientada a Objetos (OOP) que permite tratar objetos de distintas clases como objetos de una superclase común. Proporciona flexibilidad y reutilización del código.

En esta lección, aprenderá a implementar el polimorfismo en Python mediante métodos y clases.

Polimorfismo — ilustración 1

¿Qué es el polimorfismo?

¿Qué es el polimorfismo?

El polimorfismo permite que los métodos de diferentes clases compartan el mismo nombre y se comporten de manera distinta. Esto hace que el código sea más flexible y fácil de ampliar.

# 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

Polimorfismo con métodos

Polimorfismo con métodos

Los métodos con el mismo nombre en distintas clases pueden proporcionar implementaciones diferentes.

# Another subclass with its own implementation of the speak method
class Cat(Animal):
    def speak(self):
        print("Cat meows")  # Specific behavior for Cat

# Function demonstrating polymorphism
# It can accept objects of any subclass of Animal

def animal_sound(animal):
    animal.speak()  # Calls the appropriate speak method based on the object type

# Creating objects of Dog and Cat
dog = Dog()
cat = Cat()

# Calling the function with different objects
animal_sound(dog)  # Outputs: Dog barks
animal_sound(cat)  # Outputs: Cat meows

Ejemplo de polimorfismo con métodos

Polimorfismo con métodos

Los métodos con el mismo nombre en distintas clases pueden proporcionar implementaciones diferentes.

# Another subclass with its own implementation of the speak method
class Cat(Animal):
    def speak(self):
        print("Cat meows")  # Specific behavior for Cat

# Function demonstrating polymorphism
# It can accept objects of any subclass of Animal

def animal_sound(animal):
    animal.speak()  # Calls the appropriate speak method based on the object type

# Creating objects of Dog and Cat
dog = Dog()
cat = Cat()

# Calling the function with different objects
animal_sound(dog)  # Outputs: Dog barks
animal_sound(cat)  # Outputs: Cat meows

Polimorfismo con funciones

Polimorfismo con funciones

El polimorfismo permite que una misma función opere con distintos tipos de objetos.

# Defining two unrelated classes
class Bird:
    def fly(self):
        print("Bird flies")  # Behavior specific to birds

class Plane:
    def fly(self):
        print("Plane flies")  # Behavior specific to planes

# Function demonstrating polymorphism
# It can accept objects of both Bird and Plane

def flying_object(obj):
    obj.fly()  # Calls the appropriate fly method based on the object type

# Creating objects of Bird and Plane
bird = Bird()
plane = Plane()

# Calling the function with different objects
flying_object(bird)  # Outputs: Bird flies
flying_object(plane)  # Outputs: Plane flies

Polimorfismo con herencia

Polimorfismo con herencia

El polimorfismo suele lograrse mediante la herencia, donde las subclases sobrescriben métodos de la superclase.

# Superclass representing a generic vehicle
class Vehicle:
    def start(self):
        print("Vehicle starts")  # Generic behavior for all vehicles

# Subclass representing a specific type of vehicle
class Car(Vehicle):
    def start(self):
        print("Car starts")  # Specific behavior for cars

# Subclass representing another specific type of vehicle
class Bike(Vehicle):
    def start(self):
        print("Bike starts")  # Specific behavior for bikes

# Function demonstrating polymorphism
# It can accept objects of any subclass of Vehicle

def start_vehicle(vehicle):
    vehicle.start()  # Calls the appropriate start method based on the object type

# Creating objects of Car and Bike
car = Car()
bike = Bike()

# Calling the function with different objects
start_vehicle(car)  # Outputs: Car starts
start_vehicle(bike)  # Outputs: Bike starts

Ventajas del polimorfismo

Ventajas del polimorfismo

El polimorfismo ofrece varias ventajas:

  • Reutilización y flexibilidad del código.
  • Mejor legibilidad y organización del código.
  • Fomenta el uso de interfaces comunes.

Ejemplo del mundo real

Ejemplo del mundo real

A continuación, se muestra un ejemplo del mundo real que utiliza polimorfismo.

# Real-world example of polymorphism
class Developer:
    def work(self):
        print("Writing code")  # Specific task for developers

class Designer:
    def work(self):
        print("Designing user interfaces")  # Specific task for designers

# Function demonstrating polymorphism
# It can accept objects of both Developer and Designer

def workday(employee):
    employee.work()  # Calls the appropriate work method based on the object type

# Creating objects of Developer and Designer
developer = Developer()
designer = Designer()

# Calling the function with different objects
workday(developer)  # Outputs: Writing code
workday(designer)  # Outputs: Designing user interfaces

Errores comunes con el polimorfismo

Errores comunes con el polimorfismo

Estos son algunos errores que debe evitar:

  • Olvidar sobrescribir métodos en las subclases cuando sea necesario.
  • Confundir el orden de resolución de métodos (MRO) en la herencia múltiple.
  • Usar polimorfismo innecesariamente para tareas sencillas.

¿Qué aprendió?

¿Qué aprendió?

En esta lección, aprendió:

  • Qué es el polimorfismo y cómo funciona en Python.
  • Cómo implementar el polimorfismo con métodos y herencia.
  • Las ventajas de utilizar polimorfismo en la OOP.

¡Buen trabajo! Pasemos al siguiente tema.

Polimorfismo — ilustración 12

Preguntas frecuentes

¿La lección «Polimorfismo» es gratis?

Sí — el texto completo de «Polimorfismo» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Learn AI with Python, actualiza a CoddyKit PRO. El curso de Learn AI with Python incluye 6 lecciones en total.

¿Qué aprenderé en «Polimorfismo»?

Explore cómo el polimorfismo permite crear código flexible y dinámico. Practicas Learn AI with Python con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.

¿Necesito experiencia previa para empezar Learn AI with Python?

No se requiere experiencia previa. Learn AI with Python en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 4 de 6.

¿Cuánto tiempo toma la lección «Polimorfismo»?

La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.

¿Puedo escribir y ejecutar código en esta lección de Learn AI with Python?

Sí. Cada lección de Learn AI with Python incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.

Todas las lecciones de este curso

  1. Clases y objetos
  2. Atributos y métodos
  3. Herencia
  4. Polimorfismo
  5. Encapsulación y abstracción
  6. Métodos mágicos (__str__, __repr__, etc.)
← Volver a Learn AI with Python