Classes

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
        self.name = name

    def __str__(self): # special method
        return self.name

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

Now lets make few instances of our class

#Instances
Aman = Person("Aman")
Kharwal = Person("Kharwal")
# Attributes
print(Aman.species)
print(Aman.name)

#Output
Homo Sapiens
Aman

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

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

#Output
Aman
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)
print(r.area())

#Output
12
s = square(4)
print(s.area())

#Output
16

Previous||Next Chapter