Classes and Inheritance in python

Python offers itself not only as a scripting language, but also supports object oriented programming. Classes describes data and provide methods to manipulate that data, all encompassed under a single object.

Introduction to Classes

# Creating a class
class Person(object):
    species = "Homo Sapiens" #Class attribute

    def __init__(self, name): # special method = name

    def __str__(self): # special method

    def rename(self, renamed): # regular method = renamed
        print("Now My name is {}".format(

Now lets make few instances of our class

Aman = Person("Aman")
Kharwal = Person("Kharwal")
# Attributes

Homo Sapiens

We can execute the methods of the class using the same dot operator:

# Methods
print(Aman.rename("Aman Kharwal"))

Now My name is Aman Kharwal

Basic Inheritance

Inheritance in python is based on similar ideas used in other object oriented languages like java, C++ etc. A new class can be driven from an existing class as follows:

class Rectangle():
    def __init__(self, width, height):
        self.width = width
        self.height = height

   def area(self):
       return self.width * self.height

The rectangle class can be used as a base class for determining s square class, as square is a special case rectangle:

class square(Rectangle):
    def __init__(self, side): # call parent constructor, width and height are both sides
    super(square, self).__init__(side, side)
    self.side = side
r = Rectangle(3, 4)

s = square(4)


Previous||Next Chapter