logo codesdope

Overriding in Python

Override means having two methods with the same name but doing different tasks. It means that one of the methods overrides the other.
If there is any method in the superclass and a method with the same name in a subclass, then by executing the method, the method of the corresponding class will be executed.
Make it clearer with an example

class Rectangle():
	def __init__(self,length,breadth):
		self.length = length
		self.breadth = breadth
	def getArea(self):
		print self.length*self.breadth," is area of rectangle"
class Square(Rectangle):
	def __init__(self,side):
		self.side = side
	def getArea(self):
		print self.side*self.side," is area of square"
s = Square(4)
r = Rectangle(2,4)
16 is area of square
8 is area of rectangle

Since the method from the coressponding class came into action, it means that one overrode the other.
Execution of 'getArea' on the object of Rectangle (r) printed "8 is area of rectangle" from the 'getArea' defined in the Rectangle class whereas, execution of 'getArea' on the object of Square (s) printed "16 is area of square" from the 'getArea' defined in the Square class.
It is very useful because it prevents us from making methods with different names and remembering them all.

There is not much to explain in this chapter. So, it is recommended to solve questions to get things clearer.

You are only good as the chances you take.
-Al Pacino

Download Our App.
BlogsDope App
Get it on Google Play
Doubt? Ask question

Welcome.please sign up.


Welcome.please login.