Object Oriented Programming in Python

Python is an emerging programming language in today’s world which is a general-purpose, object-oriented, interactive, interpreted and high level programming language. Python supports different programming methodologies. One of the main methods is by creating objects, which is known as Object Oriented Programming (OOP). Python provisions object oriented concepts such as abstraction, encapsulation, inheritance and polymorphism. Object Oriented Programming makes the program easy to understand and efficient.

OOP’s concepts in Python emphasizes on creating a reusable code. It follows some basic terminologies such as:

Class

A class is a user-defined prototype for an object which defines a set of attributes which characterizes any object of a class. The attributes can be class variables, instance variables and methods which are accessed via dot notation. Since, class is sharable, the code can be reused.

Let’s take an example of a class ‘Animal’ which can have details about different types of animals including their name, color, size, physical structure, age, etc.

class Animal:

Here, we have used a keyword ‘class’ to define the empty class Animal. In a class, we define objects, variables, methods etc.

Object

Object is an instance of a class.

Obj = Animal()

Here, Obj is an object of a class Animal.

Creating a Class and Object in Python

class Animal:
species = “wild animal”
def __init__(self, name, color):
self.name = name
self.color = color
tiger = Animal(“Tiger”,”White”)
lion= Animal(“Lion”,”Yellow”)
print(“Tiger is a {} ”.format(tiger.__class__.species))
print(“Lion is a {} ”.format(lion.__class__.species))
print(“{} is {} in color ”.format(tiger.name,tiger.color))
print(“{} is {} in color ”.format(lion.name,lion.color))

Output:

Tiger is a wild animalLion is a wild animalTiger is White in colorLion is Yellow in color

Here, we have created a class named “Animal”. Then, we have defined the attributes of an object. Attributes are nothing but characteristics of an object.

__init()__ is an initializer method which has attributes such as name and color defined inside it. The initializer method is called first as soon as the object is created.

Afterwards, we have created two instances, i.e. objects namely, tiger and lion of the class Animal with reference values in it.

The class attributes are variables defined in a class. Here in this example, ‘species’ is a variable defined in the class Animal. We can access the class attributes by using __class__.species. We can access the instance attributes using tiger.name and tiger.color. The instance attributes are different for every instance of a class.

Method

Methods are simply functions defined inside the body of a class. Methods define behaviors of an object.

class Animal:
def __init__(self, name, color):
self.name = name
self.color = color
def run(self, ran):
return “{} runs {}”.format(self.name, ran)
def eat(self)
return “{} is eating”.format(self.name)
tiger = Animal(“Tiger”,”White”)
print(tiger.run(“ fast ”))
print(tiger.eat())

Output:

Tiger runs fastTiger is eating

In this program of Python, we have defined two methods, which are: run() and eat(). These are called instance methods as the methods are called on instance i.e. tiger.

Abstraction

Abstraction is an OOP’s concept in Python which hides the important details and shows only the essential features of the object. Data is safe and secure with abstraction.

from abc import ABC
class Polygon(ABC):
# abstract method
def sides(self):
pass
class Triangle(Polygon):
def sides(self):
print("Triangle has 3 sides..")
class Pentagon(Polygon):
def sides(self):
print("Pentagon has 5 sides..")
class Hexagon(Polygon):
def sides(self):
print("Hexagon has 6 sides..")

class square(Polygon):
def sides(self):
print("I have 4 sides..")
t = Triangle()
t.sides()
s = square()
s.sides()
p = Pentagon()
p.sides()
k = Hexagon()
K.sides()

Output:

Triangle has 3 sidesSquare has 4 sidesPentagon has 5 sidesHexagon has 6 sides

In above program, we have defined the abstract base class named Polygon and we have also defined an abstract method sides(). The base class Polygon is inherited by various subclasses. We have implemented the abstract method in each subclass. We created the object of the subclasses and invoke the method sides(). Now, the hidden implementations for the method sides() inside each subclass comes into effect. The abstract method sides(), defined in abstract class, is never invoked directly. Below are some features of the abstract class:

  • An abstract class can contain both normal and abstract methods.
  • An abstract class cannot be instantiated: we cannot create objects for the abstract class.

Inheritance

Inheritance mechanism allows one class to inherit properties of other class without modifying it. The newly created class is called child class or derived class and the existing class from which the newly created (child) class inherits the properties is called parent class.

class Animal:
def __init__(self):
print(“Animal is ready..”)
def whoisthis(self)
print(“Animal..”)
def run(self)
print(“Runs Faster..”)
class Tiger(Animal):
def __init__(self):
super().def __init__()
print(“Tiger is ready..”)
def whoisthis(self)
print(“Tiger..”)
def move(self)
print(“Moves Faster..”)
tig = Tiger()
tig.whoisthis()
tig.run()
tig.move()

Output:

Animal is ready..Tiger is ready..Tiger..Runs faster..Moves faster..

In the above Python program, there are two classes, viz. Animal (Parent Class) and Tiger (Child Class). The Child class, i.e. Tiger() inherits the properties of the base or parent class, i.e. Animal().

In the above example, super() method inside the __init__() method of the child class Tiger() allows us to run __init__() method of parent class i.e. Animal().

The child class, i.e. Tiger() modifies the behavior of parent class by defining its own whoisthis() method.

The child class, i.e. Tiger() inherits the function run() of parent class i.e. Animal.

Encapsulation

As per the Encapsulation in OOP’s (Object Oriented Programming) concept of Python, we can hide i.e. restrict access to some methods and variables in a program. This helps in preventing data from direct modifications or changes. In the Python program, we specify private attributes using underscore as a prefix, i.e. single ‘_’ or double ‘__’.

class Mobile:
def __init__(self):
self.__maxprice = 10000
def sell(self)
print(“Selling Price of Mobile is: {}”.format(self.__maxprice))
def setMaxPrice(self, price)
self.__maxprice = price
m = Mobile()
m.sell()
m.__maxprice = 12000
m.sell()
m.setMaxPrice(12000)
m.sell()

Output:

Selling Price of Mobile is: 10000Selling Price of Mobile is: 10000Selling Price of Mobile is: 12000

In the above Python program, we have defined a class Mobile().

Here, we have used __init__() method to store the maximum selling price of a Mobile. We tried to modify the price. However, we couldn’t modify the price as Python treats the __maxprice as a private attribute.

As we have seen in the above program, we have used setMaxPrice() function to set a new price. This function takes price as a parameter.

Polymorphism

Poly means many and morph means forms. In short, polymorphism is a concept that depicts one common interface in many forms.

For example, suppose we need to calculate the area for different shapes such as rectangle, circle, square, etc., then we will use a common method area() for calculating the area of rectangle, square or circle.

Let’s consider some more simple examples as below:

class Tiger:
def run(self)
print(“Tiger can run..”)
def fly(self)
print(“Tiger can’t fly..”)
class Sparrow:
def run(self)
print(“Sparrow can’t run..”)
def fly(self)
print(“Sparrow can fly..”)
def running_test(animal)
animal.run()
tig = Tiger()
spr = Sparrow()
running_test(tig)
running_test(spr)

Output:

Tiger can run..Sparrow can’t run..

In this example, we have defined two classes, viz. Tiger() and Sparrow(). Each class has two common methods named run() and fly(). However, their functions are different.

In order to use the polymorphism concept, we have created a common function called running_test() that takes any object and calls run() method. In the above example, we have passed the objects tig and spr in the function running_test and this calls run() which is common method in different forms which depicts polymorphism.

Polymorphism permits the use of the same interface for different objects which helps programmers to write code easily and efficiently.

JavaScript Developer. I am proficient in building SPA with React.js