Polimorfismo
Explore como o polimorfismo permite criar código flexível e dinâmico
Polimorfismo é uma aula grátis de Learn AI with Python no CoddyKit. Esta é a aula 4 de 6. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Learn AI with Python, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Learn AI with Python inclui 6 aulas no total.
Introdução ao polimorfismo
Introdução ao polimorfismo
O polimorfismo é um conceito fundamental da Programação Orientada a Objetos (POO) que permite tratar objetos de classes diferentes como objetos de uma superclasse comum. Ele proporciona flexibilidade e reutilização do código.
Nesta lição, você aprenderá a implementar o polimorfismo em Python usando métodos e classes.

O que é polimorfismo?
O que é polimorfismo?
O polimorfismo permite que métodos de classes diferentes compartilhem o mesmo nome, mas se comportem de maneiras diferentes. Isso torna o código mais flexível e fácil de estender.
# 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 DogPolimorfismo com métodos
Polimorfismo com métodos
Métodos com o mesmo nome em classes diferentes podem fornecer implementações distintas.
# 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 meowsExemplo de polimorfismo com métodos
Polimorfismo com métodos
Métodos com o mesmo nome em classes diferentes podem fornecer implementações distintas.
# 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 meowsPolimorfismo com funções
Polimorfismo com funções
O polimorfismo permite que a mesma função opere em diferentes 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 fliesPolimorfismo com herança
Polimorfismo com herança
O polimorfismo geralmente é obtido por meio da herança, na qual as subclasses substituem métodos da superclasse.
# 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 startsVantagens do polimorfismo
Vantagens do polimorfismo
O polimorfismo oferece vários benefícios:
- Reutilização e flexibilidade do código.
- Melhoria da legibilidade e da organização do código.
- Incentivo ao uso de interfaces comuns.
Exemplo do mundo real
Exemplo do mundo real
Veja um exemplo do mundo real usando 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 interfacesErros comuns com polimorfismo
Erros comuns com polimorfismo
Veja alguns erros que você deve evitar:
- Esquecer-se de substituir métodos em subclasses quando necessário.
- Confundir a ordem de resolução de métodos (MRO) na herança múltipla.
- Usar polimorfismo desnecessariamente em tarefas simples.
O que aprendemos?
O que aprendemos?
Nesta lição, você aprendeu:
- O que é polimorfismo e como ele funciona em Python.
- Como implementar o polimorfismo com métodos e herança.
- As vantagens de usar polimorfismo em POO.
Muito bem! Vamos passar ao próximo tópico.

Perguntas Frequentes
A aula “Polimorfismo” é grátis?
Sim — o texto completo de “Polimorfismo” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Learn AI with Python, atualize para CoddyKit PRO. O curso de Learn AI with Python inclui 6 aulas no total.
O que vou aprender em “Polimorfismo”?
Explore como o polimorfismo permite criar código flexível e dinâmico Você pratica Learn AI with Python com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.
Preciso ter experiência prévia para começar Learn AI with Python?
Nenhuma experiência prévia é necessária. Learn AI with Python no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 4 de 6.
Quanto tempo leva a aula “Polimorfismo”?
A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.
Posso escrever e executar código nesta aula de Learn AI with Python?
Sim. Cada aula de Learn AI with Python inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.
Todas as aulas deste curso
- Classes e objetos
- Atributos e métodos
- Herança
- Polimorfismo
- Encapsulamento e abstração
- Métodos mágicos (__str__, __repr__ etc.)