1.
polymorphism using inheritance in Python
class Animal:
def __init__(self, name):
[Link] = name
def speak(self):
return "Generic animal sound"
class Dog(Animal):
def speak(self):
return "Woof!"
class Cat(Animal):
def speak(self):
return "Meow!"
def animal_sound(animal):
return [Link]()
# Instances of different classes
generic_animal = Animal("Generic Animal")
dog = Dog("Buddy")
cat = Cat("Whiskers")
# Polymorphism in action
print(f"{generic_animal.name} says: {animal_sound(generic_animal)}")
print(f"{[Link]} says: {animal_sound(dog)}")
print(f"{[Link]} says: {animal_sound(cat)}")
Output:
Code
Generic Animal says: Generic animal sound
Buddy says: Woof!
Whiskers says: Meow!
[Link] in Class Methods
class Cat:
def __init__(self, name, age):
[Link] = name
[Link] = age
def info(self):
print(f"I am a cat. My name is {[Link]}. I am {[Link]} years old.")
def make_sound(self):
print("Meow")
class Dog:
def __init__(self, name, age):
[Link] = name
[Link] = age
def info(self):
print(f"I am a dog. My name is {[Link]}. I am {[Link]} years old.")
def make_sound(self):
print("Bark")
cat1 = Cat("Kitty", 2.5)
dog1 = Dog("Fluffy", 4)
for animal in (cat1, dog1):
animal.make_sound()
[Link]()
animal.make_sound()
Output
Meow
I am a cat. My name is Kitty. I am 2.5 years old.
Meow
Bark
I am a dog. My name is Fluffy. I am 4 years old.
Bark
[Link] Overriding
from math import pi
class Shape:
def __init__(self, name):
[Link] = name
def area(self):
pass
def fact(self):
return "I am a two-dimensional shape."
def __str__(self):
return [Link]
class Square(Shape):
def __init__(self, length):
super().__init__("Square")
[Link] = length
def area(self):
return [Link]**2
def fact(self):
return "Squares have each angle equal to 90 degrees."
class Circle(Shape):
def __init__(self, radius):
super().__init__("Circle")
[Link] = radius
def area(self):
return pi*[Link]**2
a = Square(4)
b = Circle(7)
print(b)
print([Link]())
print([Link]())
print([Link]())
Output
Circle
I am a two-dimensional shape.
Squares have each angle equal to 90 degrees.
153.93804002589985