python tutorial

Python Inheritance

Learn more about Python, one of the world’s most versatile and popular programming languages.

One of the many features Object Oriented Programming (OOP) languages provides is Inheritance. Just like the name suggests, it is a way for taking a Python class as a parent or base class and creating different Python child classes from it that will inherit all the attributes and methods of the parent or base class. It is very useful in sharing common attributes and methods across multiple classes.

Inheritance can be implemented by adding the parent class name inside parentheses while creating a child class.

Code Example
class ParentClass:
	'''A docstring like this explains what the parent class does'''
class ChildClass(ParentClass):
	'''A docstring like this explains what the child class does'''

Code Example
>>> class Shape:
… 	''' This is a base class Shape that allows to create shapes of all kinds'''
… 	def __init__(self):
… 		self.type = 'Shape'
… 	def __str__(self):
… 		return "This is a shape of type {}.".format(self.type)

# create an object from class Shape
# __init__ will be called while creating new objects
>>> shapeObject = Shape()
>>> print(shapeObject)
This is a shape of type Shape.

# Notice that Rectangle inherits from Shape
>>> class Rectangle(Shape):
… 	def __init__(self, length, width):
… 		self.type = 'Rectangle'
… 		self.length = length
… 		self.width = width
… 	def calculate_area(self):
… 		return self.length * self.width
>>> rectangleObject = Rectangle(10, 20)
>>> print(rectangleObject)
This is a shape of type Rectangle
>>> print('Area of Rectangle is: ', rectangleObject.calculate_area())
Area of Rectangle is: 200

Learn Python Today

Get hands-on experience writing code with interactive tutorials in our free online learning platform.

  • Free and fun
  • Designed for beginners
  • No downloads or setup required