Python Function Overriding

Function overriding is a feature in Python (and other object-oriented programming languages) that allows a subclass to provide a different implementation of a method that is already defined in its superclass. When a method in a subclass has the same name and parameters as a method in its superclass, it is said to be "overriding" the superclass method.


Here's an example of function overriding in Python:

class Animal:
	def make_sound(self):
		print("Generic animal sound")

class Dog(Animal):
	def make_sound(self):
		print("Woof!")

class Cat(Animal):
	def make_sound(self):
		print("Meow!")

my_dog = Dog()
my_cat = Cat()
my_dog.make_sound() # Output: Woof!
my_cat.make_sound() # Output: Meow!

In this example, we have a base class Animal with a method make_sound(), which prints a generic animal sound. The Dog and Cat classes both inherit from Animal and override the make_sound() method with their own implementations.

When we create instances of Dog and Cat and call their make_sound() methods, we get the outputs "Woof!" and "Meow!" respectively, instead of the generic animal sound.

In summary, function overriding allows subclasses to customize the behaviour of a superclass method according to their own needs, which can make code more flexible and reusable.



About the Author



Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.

We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc






 PreviousNext