Polymorphism in Python
- Get link
- X
- Other Apps
Polymorphism in Python
Polymorphism is a fundamental concept in object-oriented programming that allows objects of different classes to be treated as if they are objects of the same class. In Python, polymorphism is achieved through method overloading and method overriding.
Method overloading is the ability to define methods with the same name but different parameters. Python does not support method overloading in the same way as some other programming languages, but you can use default values for function arguments to achieve a similar effect. For example:
class MyClass: def my_method(self, a=None, b=None): if a is not None and b is not None: return a + b elif a is not None: return a else: return 0
In the example above, we define a method my_method()
with two optional arguments a
and b
. If both a
and b
are provided, the method returns their sum. If only a
is provided, the method returns a
. If neither a
nor b
is provided, the method returns 0.
Method overriding is the ability to define a method in a subclass with the same name as a method in the superclass, and to use the new implementation of the method instead of the old one. For example:
class Animal: def make_sound(self): print("Generic animal sound") class Cat(Animal): def make_sound(self): print("Meow!") class Dog(Animal): def make_sound(self): print("Woof!")
In the example above, we define a superclass Animal
with a method make_sound()
, and two subclasses Cat
and Dog
that override the make_sound()
method with their own implementation. When we call the make_sound()
method on a Cat
object, it will print "Meow!", and when we call it on a Dog
object, it will print "Woof!".
Polymorphism allows us to write code that works with objects of different classes without knowing their exact type. For example:
def make_animal_sound(animal): animal.make_sound() cat = Cat() dog = Dog() make_animal_sound(cat) # Output: Meow! make_animal_sound(dog) # Output: Woof!
make_animal_sound()
that takes an object of type Animal
or a subclass of Animal
, and calls its make_sound()
method. We create a Cat
object cat
and a Dog
object dog
, and pass them to the make_animal_sound()
function. The function works correctly with both objects, even though they are of different classes, because they both have a make_sound()
method that can be called using polymorphism.- Get link
- X
- Other Apps
Comments