Python
In this tutorial we will learn about method overriding in Python.
When a method in a child class has the same name and type signature as a method in the parent class then the child class method is said to override the parent class method and this is method overriding.
In the following Python program we are overriding the greetings
method of the parent class Awesome
in the child class SuperAwesome
.
# parent class
class Awesome:
def greetings(self, message = "Hello World"):
print("Greetings from Awesome:", message)
# child class
class SuperAwesome(Awesome):
# overriding the method of the parent class
def greetings(self, message = None):
if message != None:
print("Greetings from SuperAwesome:", message)
else:
print("Greetings from SuperAwesome!")
# objects
pObj = Awesome() # parent class object
cObj = SuperAwesome() # child class object
# method call
pObj.greetings()
pObj.greetings('Hello!!!')
cObj.greetings()
cObj.greetings('Hello!!!')
On executing the above code we will get the following output.
Greetings from Awesome: Hello World
Greetings from Awesome: Hello!!!
Greetings from SuperAwesome!
Greetings from SuperAwesome: Hello!!!
In the above code the greetings
method of the parent class is overridden in the child class.
We are creating an object using the parent class and an object using the child class.
First, we are calling the greetings method of the parent class using the parent class object pObj
. This gives us the first two lines of the output.
Next, we are calling the greetings method via the child class object cObj
and we get the last two lines of the output.
We use the super()
method to call the overridden method of the parent class from inside the child class.
In the following Python program we are calling the overridden method of the Awesome class from inside the SuperAwesome child class.
# parent class
class Awesome:
def greetings(self, message = "Hello World"):
print("Greetings from Awesome:", message)
# child class
class SuperAwesome(Awesome):
# overriding the method of the parent class
def greetings(self, message = None):
if message != None:
print("Greetings from SuperAwesome:", message)
# calling the overridden parent class greetings method
super().greetings(message)
else:
print("Greetings from SuperAwesome!")
# objects
cObj = SuperAwesome() # child class object
# method call
cObj.greetings()
cObj.greetings('Hello!!!')
The above code will give us the following output.
Greetings from SuperAwesome!
Greetings from SuperAwesome: Hello!!!
Greetings from Awesome: Hello!!!
ADVERTISEMENT