Polymorphism
Polymorphism:
class Dog(Animal):
#All methods and attributes of Animal are inherited and it has it's own characteristics as well.
class Bird(Animal):
#All methods and attributes of Animal are inherited and it has it's own characteristics as well.
class Lion(Animal):
#All methods and attributes of Animal are inherited and it has it's own characteristics as well.
usage example:
zoo: Animal = []
dog = Dog()
zoo.append(dog) -> it will work as dog is child of Animal
dog = Animal() -> it will also work as dog is type of Animal.
dog2 = Dog()
bird = Bird()
lion = Lion()
zoo.append(bird)
zoo.append(dog2)
zoo.append(lion)
Now overriding the method in child class:
class Animal:
def talk(self):
print("Does not make a sound")
class Dog(Animal):
def talk(self):
print("Bark!")
class Bird(Animal):
def talk(self):
print("Chirp!")
class Lion(Animal):
def talk(self):
print("Roar!")
Verification:
for animal in zoo:
animal.talk()
Implementing polymorphism in our small game code:
- Create new battle function within our main.py file
- Uses our enemy talk() and attack() methods
Code example:
# using implementation
from Enemy import Enemy
from Zombie import Zombie
from Ogre import Orge
def battle(e: Enemy): # We are passing parent object as parameter
e.talk()
e.attack()
zombie=Zombie(healthPoints=15, attack_damage=3)
"""
# This will call the getter method for typeOfEnemy
print(f"Enemy type = {zombie.get_typeOfEnemy()}")
# This will call the talk method from the Zombie class
print(f"{zombie.talk()}")
# This will call the spread_diesease method from the Zombie class
print(f"{zombie.spread_diesease()}")
"""
ogre=Orge(healthPoints=25, attack_damage=7)
"""
# This will call the getter method for typeOfEnemy
print(f"Enemy type = {ogre.get_typeOfEnemy()}")
# This will call the talk method from the Ogre class
print(f"{ogre.talk()}")
"""
battle(zombie)
battle(ogre)

Comments
Post a Comment