Object Oriented Programming
In Python
Mr. Sushant Joshi
Assistant Professor , TIPS
Classes
A class is like a blueprint or template for creating objects.
It defines how something should look (its attributes) and what
it can do (its methods).
Example:
Think of a class as a “Car Design.”
It describes features like color, model, speed, and functions like
start() or stop().
Syntax of Classes :
class ClassName:
# class body
# data members (variables)
# member functions (methods)
Code of Classes
class Student:
def __init__(self, name, age):
[Link] = name
[Link] = age
def display(self):
print("Name:", [Link])
print("Age:", [Link])
Object
An object is an instance of a class.
It represents a real-world entity and contains the
actual values for the variables defined in the class.
Syntax of Objects
object_name = ClassName(arguments)
Code of Objects
s1 = Student(“Thor", 25)
[Link]()
Output :
Name: Thor
Age: 25
Attributes and Methods
Attributes are variables that belong to a class or an object.
They are used to store data or characteristics of the object.
Types of Attributes:
1. Instance Attributes:
Belong to a specific object.
Defined inside the constructor (__init__() method) using self.
Each object can have different values for these attributes.
2. Class Attributes:
Shared by all objects of the class.
Defined outside the constructor but inside the class.
Code of Attributes
class Car:
wheels = 4 # Class Attribute
Output :
def __init__(self, brand, color):
Toyota Red 4
[Link] = brand # Instance Attribute
BMW Black 4
[Link] = color # Instance Attribute
# Creating objects Explanation:
car1 = Car("Toyota", "Red") brand and color are instance attributes
car2 = Car("BMW", "Black")
(different for each car).
wheels is a class attribute (same for all cars).
print([Link], [Link], [Link])
print([Link], [Link], [Link])
Methods are functions that are defined inside a class and used to
perform operations or actions on the data (attributes).
They define the behavior of the object.
Types of Methods:
1. Instance Methods: Work with instance attributes using self.
2. Class Methods: Work with class attributes using @classmethod
and cls.
3. Static Methods: General utility functions, defined using
@staticmethod.
Code of Methods
class Student:
school = "ABC Public School" # Class Attribute
def __init__(self, name, marks):
[Link] = name
[Link] = marks
def display(self): # Instance Method
print("Name:", [Link])
print("Marks:", [Link])
@classmethod
def school_info(cls): # Class Method
print("School Name:", [Link])
@staticmethod
def greet( ): # Static Method
print("Welcome to the School!")
Usage of Methods
s1 = Student(“Thor", 29)
[Link]()
Student.school_info()
[Link]()
Constructors
It is a special method that is automatically invoked when an object of a
class is created. It is primarily used to initialize the attributes of the class
with specific values at the time of object creation. The constructor in
python is defined using the special method __init__( ). This method plays a
vital role in object-oriented programming as it allows objects to begin their
life in a well-defined state.
Syntax of Constructors :
class ClassName:
def __init__(self, parameter1, parameter2, ...):
self.attribute1 = parameter1
self.attribute2 = parameter2
When an object is created, the __init__( ) method is called automatically, passing the
object itself as the first argument (self), followed by any other arguments supplied during
object creation. The keyword self refers to the current instance of the class and is used
to access variables and methods belonging to the class.
Example :
class Student:
def __init__(self, name, age):
[Link] = name
[Link] = age
s1 = Student(“Thor", 20)
print("Name:", [Link])
print("Age:", [Link])
Types of Constructors in Python
1. Default Constructor:
A constructor that does not accept any arguments except self. It initializes the
object with default values.
class Demo:
def __init__(self):
[Link] = "Default Constructor"
2. Parameterized Constructor:
A constructor that takes parameters to initialize the object with specific
values.
class Demo:
def __init__(self, message):
[Link] = message
Importance of Constructors
1. Automatic Initialization of Objects
A constructor is automatically called when an object is created, which eliminates
the need to call an initialization function manually. This ensures that the object’s
attributes are assigned valid values right at the time of creation. For example, when
a Student object is created, the constructor immediately assigns values such as
name, age, or roll number. This automatic process reduces the chances of errors and
makes code cleaner and more reliable.
2. Promotes Code Reusability and Maintainability
Constructors help avoid code repetition by allowing the same initialization logic to
be reused across multiple objects. Once defined inside a class, the constructor can
initialize as many objects as needed with different values. This not only improves
code efficiency but also makes maintenance easier—if the initialization process
changes, it only needs to be updated in one place (the constructor), not across
multiple instances of code.
3. Supports Data Encapsulation and Security
Constructors often initialize private or protected variables that cannot be
accessed directly from outside the class. By doing so, they help enforce
data encapsulation, one of the core principles of OOP. This ensures that
sensitive data remains secure and can only be modified through controlled
methods, maintaining data integrity throughout the program.
4. Enhances Program Readability and Object Clarity
Using constructors makes code more readable and organized. When an
object is created with a constructor, it becomes immediately clear what
data or attributes that object will contain. This improves program clarity
and helps developers understand the structure and purpose of each object
without having to trace the code manually.
Static Methods
They are special types of methods that belong to a class rather than to any
specific instance of the class. They are defined within a class but do not
require access to the instance (self) or the class (cls) variables. This means
that static methods cannot modify or access the state of the class or its
objects.
A static method is defined using the @staticmethod decorator before the
method definition. Such methods are mainly used when some processing is
related to the class but does not need to access class attributes or instance
attributes. They are useful for performing utility tasks, calculations, or
operations that logically belong to the class but are independent of object
data.
Note : Static methods can be called directly using the class name, without
creating an object of the class.
Encapsulation
It is a fundamental principle of Object-Oriented Programming (OOP) that focuses on
binding the data (variables) and methods (functions) that operate on that data into
a single unit, known as a class. It helps in restricting direct access to some of the
object’s components, thereby ensuring controlled interaction with the data. The main
purpose of encapsulation is to safeguard the internal state of an object from
unintended or unauthorized modifications. In Python, encapsulation is achieved
through access specifiers such as public, protected, and private members. Public
members are accessible from anywhere in the program, protected members are
accessible within the class and its subclasses, and private members are accessible only
within the class itself. Private members are defined by prefixing the variable or
method name with a double underscore (__).
Encapsulation promotes the concept of data hiding, which means that the internal
representation of an object is kept hidden from the outside world. This ensures
that the data can only be modified through well-defined interfaces, usually through
getter and setter methods.
Example of Encapsulation
class Student: # Object creation
def __init__(self, name, age): s1 = Student("John", 20)
self.__name = name # Private variable
self.__age = age # Private variable # Accessing private data using getter
print("Student Age:", s1.get_age())
def get_age(self):
# Modifying private data using setter
return self.__age # Getter method
s1.set_age(22)
print("Updated Age:", s1.get_age( ))
def set_age(self, age):
if age > 0:
Output :
# Setter method to modify data safely Student Age: 20
self.__age = age Updated Age: 22
Inheritance
It is an important concept in Object-Oriented Programming (OOP) that allows a
new class to derive or acquire the properties and behaviors (methods and
attributes) of an existing class. It promotes the concept of reusability and
extensibility of code. The class whose properties are inherited is known as the
parent class or base class, and the class that inherits these properties is called
the child class or derived class.
By using inheritance, developers can create a hierarchy of classes that share
common features, reducing redundancy and improving code organization. The
child class can use all the features of the parent class and can also define
additional attributes or methods of its own. Moreover, it can modify or override
the behavior of parent class methods to suit specific requirements. In Python,
inheritance is implemented by passing the parent class name as an argument in
the child class definition.
Syntax of Inheritance
class ParentClass:
# parent class body
pass
class ChildClass(ParentClass):
# child class body
pass
Types of Inheritance in Python
1. Single Inheritance: 2. Multiple Inheritance:
In this type, a child class inherits from a single parent A child class can inherit from more than one parent class.
class.
class Father:
class Parent:
def skill(self):
def display(self):
print("Skilled in driving.")
print("This is the parent class.")
class Mother:
class Child(Parent): def talent(self):
def show(self): print("Skilled in coding.")
print("This is the child class.") class Child(Father, Mother):
pass
obj = Child() obj = Child()
[Link]() [Link]()
[Link]() [Link]()
3. Multilevel Inheritance: 4. Hierarchical Inheritance:
In this type, a class inherits from another class which Multiple child classes inherit from a single parent
itself is derived from a different class, forming a chain.
class.
class Grandparent:
class Parent:
def display(self):
def message(self):
print("Grandparent class.")
print("Parent class message.")
class Parent(Grandparent):
pass class Child1(Parent):
pass
class Child(Parent):
pass
class Child2(Parent):
pass
obj = Child()
[Link]()
Polymorphism
It is one of the fundamental concepts of Object-Oriented Programming (OOP) that
allows objects of different classes to be treated as objects of a common superclass.
The term polymorphism is derived from two Greek words — poly meaning “many”
and morph meaning “forms.” Hence, polymorphism refers to the ability of a single
function, method, or operator to perform different operations depending on the type of
objects or data it is applied to.
In Python, polymorphism provides flexibility and reusability of code by allowing the
same interface to be used for different data types or class objects. This means that
different classes can define methods with the same name, and these methods can
behave differently depending on the object that invokes them.
For example, consider two classes, Dog and Cat, both having a method named
sound(). Even though the method name is the same, each class provides its own
implementation. When the method is called, Python automatically determines which
version to execute based on the object type.
Example of Polymorphism
class Dog:
def sound(self):
return "Barks"
class Cat:
def sound(self):
return "Meows"
# Creating objects
d = Dog()
c = Cat()
# Same method name behaving differently
print([Link]()) # Output: Barks
print([Link]()) # Output: Meows
Introduction to NumPy
NumPy stands for Numerical Python, is one of the most powerful and fundamental
libraries in Python used for numerical and scientific computing. It provides support for
working with large, multi-dimensional arrays and matrices, along with a wide collection
of mathematical, logical, and statistical functions to operate on these arrays efficiently.
NumPy serves as the foundation for many advanced data analysis, machine learning, and
scientific computing libraries such as Pandas, SciPy, and TensorFlow.
The primary object in NumPy is the ndarray (n-dimensional array), which allows users to
store and manipulate numerical data in a structured and efficient manner. Unlike Python’s
built-in lists, NumPy arrays are homogeneous, meaning all elements in an array are of the
same data type. This uniformity ensures faster computation and better memory
management.
NumPy also supports a wide range of mathematical operations such as trigonometric
functions, logarithms, exponentiation, random number generation, and linear algebra
operations like matrix multiplication, eigenvalues, and determinants. These built-in
functions make NumPy an essential tool for students, researchers, and professionals
working in data science and computational fields.
Why is NumPy Faster Than Lists?
1. Implemented in C : NumPy operations are written in optimized C code, so
computations happen at the machine level, not through Python’s slower interpreter.
2. Homogeneous Data : NumPy arrays store elements of the same data type,
allowing efficient memory storage and faster access, unlike Python lists that can hold
mixed types.
3. Contiguous memory : Elements in a NumPy array are stored in contiguous blocks
of memory, which speeds up iteration and mathematical operations.
4. Vectorization(Whole Array Operations) : NumPy performs operations on entire
arrays (vectorized operations) instead of looping through elements one by one in
Python.
5. Avoids overhead of Python loops : Since most operations are handled internally
in C, there’s no need for explicit Python loops, which are slow.
6. Optimized broadcasting : NumPy uses broadcasting to perform arithmetic
between arrays of different shapes efficiently without making extra copies.
Array Creation Functions
(NumPy provides several functions to create arrays in different ways.)
1. [Link]( ) : Used to create an array from a 4. [Link]( ) : Creates an array filled with
list or tuple. ones.
import numpy as np arr = [Link](5)
arr = [Link]([1, 2, 3, 4, 5]) print(arr)
print(arr)
5. [Link]( ) : Creates an array with evenly
2. [Link]( ) : Creates an array with evenly spaced values between a start and end point.
spaced values within a given range.
arr = [Link](0, 1, 5)
arr = [Link](1, 10, 2) # Start=1, Stop=10,
Step=2 print(arr)
print(arr)
3. [Link]( ) : Creates an array filled with
zeros.
arr = [Link](5)
print(arr)
2. Mathematical Functions
(NumPy provides a wide range of mathematical functions that can be directly
applied to arrays without the need for explicit looping.)
1. [Link]( ), [Link]( ), [Link]( ), [Link]( ) :
Perform element-wise arithmetic operations.
a = [Link]([10, 20, 30]) 3. [Link]( ) : Raises each element to a specified power.
print([Link](a, 2))
b = [Link]([5, 10, 15])
print([Link](a, b)) # [15 30 45]
print([Link](a, b)) # [5 10 15]
2. [Link]( ) : Computes the square root of each
element.
print([Link](a))
3. Aggregate Functions
(Aggregate or statistical functions are used to perform summary calculations over arrays.)
•[Link]( ) : Returns the sum of all elements.
•[Link]( ) : Returns the average (mean) value.
•[Link]( ) : Returns the median value.
•[Link]( ) and [Link]( ) : Return the smallest and largest
element, respectively.
•[Link]( ) : Returns the standard deviation.
Code :
arr = [Link]([10, 20, 30, 40, 50])
print([Link](arr))
print([Link](arr))
print([Link](arr))
4. Array Manipulation Functions
(These functions help in modifying the structure, shape, or content of arrays.)
Examples:
[Link]() – Changes the shape of an array without changing its data.
[Link]() – Joins two or more arrays.
[Link]() – Converts a multi-dimensional array into a one-dimensional array.
Example:
arr = [Link]([[1, 2], [3, 4]])
print([Link](4))
Creation of One-Dimensional Arrays
In Python, one-dimensional arrays are linear collections of elements
that are stored under a single variable name and accessed using their
index values. Each element in a one-dimensional array is stored in a
contiguous memory location and can be of the same data type, such
as integers, floats, or strings.
Although Python does not have a built-in array data structure like
some other programming languages, it provides several ways to
create and manipulate arrays. The two most common methods are by
using the list data structure and the NumPy library.
Creation of One-Dimensional Arrays
1. Using Python Lists
A list in Python can act as a simple one-dimensional array. Lists are
flexible and can hold elements of different data types, though for
numerical operations, it is recommended to use NumPy arrays.
Example:
# Creating a one-dimensional array using a list
arr = [10, 20, 30, 40, 50]
# Accessing elements
print(arr[0]) # Output: 10
print(arr[2]) # Output: 30
2. Using the NumPy Library
The NumPy (Numerical Python) library provides a more efficient and
powerful way to create and manipulate arrays. NumPy arrays are
homogeneous, meaning all elements must be of the same data type, which
makes them faster and more suitable for numerical computations.
Example:
import numpy as np
# Creating a one-dimensional array using NumPy
arr = [Link]([10, 20, 30, 40, 50])
# Displaying the array
print(arr)
3. Array Creation Using Range Functions
NumPy also provides functions like [Link]( ) and [Link]( ) for creating
one-dimensional arrays easily.
1. Example using [Link]( ):
import numpy as np
arr = [Link](1, 11) # Creates an array from 1 to 10
print(arr)
2. Example using [Link]( ):
arr = [Link](0, 1, 5) # Creates 5 equally spaced values between 0 and 1
print(arr)
Introduction to Matplotlib
It is a powerful and widely used data visualization library in
Python that enables users to create static, animated, and
interactive plots. It is primarily used for representing data
in graphical form, which helps in better understanding,
analysis, and interpretation of complex datasets. Matplotlib
provides a wide variety of visualization options such as line
graphs, bar charts, histograms, pie charts, scatter plots, and
many more, making it an essential tool for data science,
analytics, and machine learning applications.
Key Features of Matplotlib
► Versatility: Supports multiple types of plots such as line, bar,
scatter, and pie charts.
► Customization: Provides control over figure size, line styles,
colors, and fonts.
► Integration: Works seamlessly with NumPy, Pandas, and
SciPy libraries.
► Interactivity: Allows for zooming, panning, and saving plots
in different formats.
► Publication Quality: Enables creation of professional,
high-quality figures suitable for academic and industry
reports.
Common Types of Plots
1. Line Plot: Used to visualize trends over time or continuous
data.
2. Bar Graph: Represents categorical data using rectangular
bars.
3. Pie Chart: Displays data as proportions of a whole.
4. Histogram: Shows the frequency distribution of a dataset.
5. Scatter Plot: Used to visualize the relationship between two
numerical variables.
Installing & Importing Matplotlib
1. Installing Matplotlib
Before using Matplotlib, it must be installed in the Python environment. This can
be done using the following command:
pip install matplotlib
2. Importing Matplotlib
Once installed, Matplotlib can be imported in a Python program as follows:
import [Link] as plt
Here, the alias plt is a common convention used by most developers for
simplicity.
Bar Graphs in Matplotlib
A Bar Graph (or Bar Chart) is used to represent categorical data
with rectangular bars, where the length or height of each bar
corresponds to the value it represents. It is mainly used for
comparing quantities across different categories. Matplotlib
provides the function [Link]( ) to draw bar graphs. You can
customize bars using colors, labels, and widths.
Syntax:
[Link](x, height, color, width, label)
Parameters:
1. x: Categories or names of bars (x-axis values).
2. height: Heights of bars (y-axis values).
3. color: Used to specify bar colors.
4. width: Defines the width of each bar (default is 0.8).
5. label: Assigns a label to the dataset for the legend.
Pie Charts in Matplotlib
A Pie Chart is a circular chart divided into slices, where each
slice represents a category’s contribution to the whole. It is
ideal for showing percentage or proportional data.
Matplotlib provides the function [Link]( ) to create pie charts.
Syntax:
[Link](data, labels, colors, autopct, startangle, explode)
Parameters:
data: Values for each slice.
labels: Names of categories.
colors: Defines colors for each slice.
autopct: Displays percentage values on the chart (e.g., "%1.1f%%").
startangle: Rotates the starting angle of the chart.
explode: Highlights a particular slice by pulling it outward.