A Quick Guide on OOPs Concept in Python

Jay Jain
CodeX
Published in
6 min readJul 23, 2021
Overview

There are many articles available on internet covering this topic, I have tried my best to cover the overview of the OOPs concept in the form of Quick Guide

What is OOPs?

Object-oriented programming (OOP) is a programming paradigm based on the concept of “objects”, which may contain data, in the form of fields, often known as attributes; and code, in the form of procedures, often known as methods.

For example, a person is an object which has certain properties such as height, gender, age, etc. It also has certain methods such as move, talk, and so on.

Building Blocks of OOPs

  • Objects
  • Class
  • Inheritance
  • Polymorphism
  • Abstraction
  • Encapsulation

What are Objects?

The object is an entity that has state and behavior. It may be any real-world object like the mouse, keyboard, chair, table, pen, etc.

Everything in Python is an object, and almost everything has attributes and methods. All functions have a built-in attribute __doc__, which returns the docstring defined in the function source code

When we define a class only the description or a blueprint of the object is created. There is no memory allocation until we create its object.

What is Class?

A class is a blueprint for that object.

We can think of a class as a sketch (prototype) of a house. It contains all the details about the floors, doors, windows, etc. Based on these descriptions we build the house. House is the object.

As many houses can be made from a house’s blueprint, we can create many objects from a class. An object is also called an instance of a class and the process of creating this object is called instantiation.

Defining a Class and Object in Python

Like function definitions begin with the def keyword in Python, class definitions begin with a class keyword.

For example:

class employee:
age = 30
designation = Manager
def greet(self):
print('Hello')

We saw that the class object could be used to access different attributes.

It can also be used to create new object instances (instantiation) of that class. The procedure to create an object is similar to a function call.

emp_obj = employee()

This will create a new object instance named emp_obj. We can access the attributes of objects using the object name prefix.
Attributes may be data or method. Methods of an object are corresponding functions of that class.
This means to say, since employee.greet is a function object (attribute of class), employee.greet will be a method object.

The word “Self”

The self is used to represent the instance of the class.
With this keyword, you can access the attributes and methods of the class in python. It binds the attributes with the given arguments.
self is also used to refer to a variable field within the class. Let’s take an example and see how it works:

class Office:

# name made in constructor
def __init__(self, US):
self.location = US

def office_location(self):
return self.location

Inheritance

Inheritance is the procedure in which one class inherits the attributes and methods of another class.
The class whose properties and methods are inherited is known as the Parent class. And the class that inherits the properties from the parent class is the Child class.

Basic Syntax:

class parent:
statements

class child(parent):
statements

In an inherited subclass, a parent class can be referred to with the use of the super() function. The super function returns a temporary object of the superclass that allows access to all of its methods to its child class.

Types of Inheritance

  1. Single Inheritance
    Single inheritance enables a derived class to inherit properties and behavior from a single parent class. It allows a derived class to inherit the properties and behavior of a base class, thus enabling code reusability as well as adding new features to the existing code.
  2. Multiple Inheritance
    A class can be derived from more than one base class in Python, similar to C++. This is called multiple inheritance.
    In multiple inheritance, the features of all the base classes are inherited into the derived class. The syntax for multiple inheritance is similar to single inheritance.
  3. Multi-level Inheritance
    We can also inherit from a derived class. This is called multilevel inheritance. It can be of any depth in Python.
    In multilevel inheritance, features of the base class and the derived class are inherited into the new derived class.
  4. Hierarchical Inheritance
    When more than one derived classes are created from a single base this type of inheritance is called hierarchical inheritance. In this program, we have a parent (base) class and two child (derived) classes.
  5. Hybrid Inheritance
    Inheritance consisting of multiple types of inheritance is called hybrid inheritance

Polymorphism

Polymorphism means multiple forms. In python we can find the same operator or function taking multiple forms.
It also useful in creating different classes which will have class methods with same name. That helps in re-using a lot of code and decreases code complexity.
Polymorphism is also linked to inheritance as we will see in some examples below.

class Square:
side = 5
def area_sq(self):
return self.side * self.side
class Triangle:
base = 5
height = 2
def area_tri(self):
return 0.5 * self.base * self.height
sq = Square()
tri = Triangle()
print("Area of square: ", sq.area_sq())
print("Area of triangle: ", tri.area_tri())
Output:
Area of square: 25
Area of triangle: 5.0

Abstraction

Abstraction in Python is the process of hiding the real implementation of an application from the user and emphasizing only on usage of it.
For example, consider you have bought a new electronic gadget. Along with the gadget, you get a user guide, instructing how to use the application, but this user guide has no info regarding the internal working of the gadget.

Through the process of abstraction in Python, a programmer can hide all the irrelevant data/process of an application in order to reduce complexity and increase efficiency.

In Python, abstraction can be achieved by using abstract classes and methods in our programs.

Abstract methods do not contain any implementation. Instead, all the implementations can be defined in the methods of sub-classes that inherit the abstract class.
An abstract class is created by importing a class named ‘ABC’ from the ‘abc’ module and inheriting the ‘ABC’ class.
Below is the syntax for creating the abstract class.

Syntax
from abc import ABC
Class ClassName(ABC):

Encapsulation

Encapsulation in Python is the process of wrapping up variables and methods into a single entity. In programming, a class is an example that wraps all the variables and methods defined inside it.

In Python, Encapsulation can be achieved by declaring the data members of a class either as private or protected. In Python, ‘Private’ and ‘Protected’ are called Access Modifiers, as they modify the access of variables or methods defined in a class

Example:

class Computer:def __init__(self):
self.__maxprice = 900
def sell(self):
print("Selling Price: {}".format(self.__maxprice))
def setMaxPrice(self, price):
self.__maxprice = price
c = Computer()
c.sell()
# change the price
c.__maxprice = 1000
c.sell()
# using setter function
c.setMaxPrice(1000)
c.sell()
Output:
Selling Price: 900
Selling Price: 900
Selling Price: 1000

In the above program, we defined a Computer class.

We used __init__() method to store the maximum selling price of Computer. We tried to modify the price. However, we can't change it because Python treats the __maxprice as private attributes.

As shown, to change the value, we have to use a setter function i.e setMaxPrice() which takes price as a parameter.

Conclusion:

  • Object-Oriented Programming makes the program easy to understand as well as efficient.
  • Since the class is sharable, the code can be reused.
  • Data is safe and secure with data abstraction.
  • Polymorphism allows the same interface for different objects, so programmers can write efficient code.

--

--

Jay Jain
CodeX
Writer for

Senior Data Engineer at Exponentia AI | AWS Certified Solution Architect | BI Tool | ETL | Spark | AWS Glue | Data Warehouse | Big Data