0% found this document useful (0 votes)
167 views3 pages

Polimorfismo Python

Polymorphism in Python refers to the ability of a function or method to behave differently depending on the type of object it is called on. This is achieved through inheritance, where a child class can override the methods of its parent class. The speak() method behaves differently depending on the type of object it is called on, printing different messages for Humans, Lions, and Cats.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
167 views3 pages

Polimorfismo Python

Polymorphism in Python refers to the ability of a function or method to behave differently depending on the type of object it is called on. This is achieved through inheritance, where a child class can override the methods of its parent class. The speak() method behaves differently depending on the type of object it is called on, printing different messages for Humans, Lions, and Cats.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

POLYMORPHISM

A R U N A R U N I S T O
Polymorphism in Python refers to the ability
of a function or method to behave
differently depending on the type of object
it is called on. This is achieved through
inheritance, where a child class can override
the methods of its parent class.

class Humans:
def __init__(self, name):
self.name = name
def speak(self):
print("Hi, my name is : ",self.name)
class Lion:
def speak():
print("Roarrrrr......")
class Cat:
def speak():
print("Meowwwww!!")

people = Humans("Arun Arunisto")


people.speak() #Hi, my name is : Arun Arunisto
li = Lion
li.speak() #Roarrrrr......
ca = Cat
ca.speak() #Meowwwww!!
As you can see, the speak() method behaves
differently depending on the type of object
it is called on. When it is called on a human's
object, it prints "Hi, my name is" with the
name. When it is called on a Lion object, it
prints "Roarrrr......!". And when it is called on
a Cat object, it prints "Meowwwwwww!".
This is because the speak() method has been
overridden in the Lion and Cat classes.
Polymorphism is a powerful feature of
object-oriented programming. It allows us to
write code that is more flexible and reusable.
By using polymorphism, we can write code
that can be used with different types of
objects without having to change the code
itself.
If you are new to object-oriented
programming, polymorphism can be a bit
confusing at first. However, once you
understand the basics, you will see that it is
a powerful tool that can help you to write
better code.

You might also like