OOP
1 Notes
The word polymorphism means having many forms. In programming, polymorphism means the same function name (but different signatures) being uses for different types. Example: # len() being used for a string print(len("geeks")) # len() being used for a list print(len([10, 20, 30])) -------------------------------------------------------------- # A simple Python function to demonstrate Polymorphism def add(x, y, z=0): return x + y + z print(add(2, 3)) print(add(2, 3, 4)) -------------------------------------------------------------- Polymorphism in addition operator: num1 = 1 num2 = 2 print(num1 + num2) str1 = "Python" str2 = "Programming" print(str1 + " " + str2) -------------------------------------------------------------- Function Polymorphism: print(len("Programiz")) print(len(["Python", "Java", "C"])) print(len({"Name": "John", "Address": "Nepal"})) -------------------------------------------------------------- Polymorphism in Class Methods: class Cat: def __init__(self, name, age): self.name = name self.age = age def info(self): print(f"I am a cat. My name is {self.name}. I am {self.age} years old.") def make_sound(self): print("Meow") class Dog: def __init__(self, name, age): self.name = name self.age = age def info(self): print(f"I am a dog. My name is {self.name}. I am {self.age} 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() animal.info() animal.make_sound() Here, we have created two classes Cat and Dog. They share a similar structure and have the same method names info() and make_sound(). However, notice that we have not created a common superclass or linked the classes together in any way. Even then, we can pack these two different objects into a tuple and iterate through it using a common animal variable. It is possible due to polymorphism. --------------------------------------------------------------