UNIT-III
OOPS CONCEPT
Object-Oriented Programming
Object-Oriented Programming is a programming paradigm where:
• Everything is represented as objects
• Objects are instances of classes
• It emphasizes reusability, modularity, and organization
Python supports OOP principles and allows you to create classes and objects
1. Class
• A class is a blueprint for creating objects.
• It defines properties (attributes) and behaviors (methods).
Example:
class Person:
pass
2. Object
• An object (or instance) is a specific realization of a class.
• Created by calling the class.
Example:
person1 = Person()
Main Principles of OOP
1. Encapsulation
• Bundling data (attributes) and methods that operate on the data into a single unit (class).
• Helps restrict direct access to some of an object's components.
2. Inheritance
• A class (child or subclass) can inherit attributes and methods from another class (parent
or superclass).
• Facilitates code reusability.
3. Polymorphism
• Same interface (method name) can be used for different underlying data types or classes.
• Methods can be overridden in subclasses.
4. Abstraction
• Hiding complex implementation details and showing only essential features.
Creating Classes and Objects
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def display_info(self):
print(f"Name: {self.name}, Age: {self.age}")
# Creating objects
person1 = Person("Alice", 25)
person2 = Person("Bob", 30)
# Calling methods
person1.display_info()
person2.display_info()
Important Features
1. __init__() Method
• Constructor method used for initializing objects.
• Runs automatically when an object is created.
2. self
• Represents the current instance of the class.
• Used to access attributes and methods within the class.
Example: Class with methods and attributes
class Car:
def __init__(self, brand, model):
self.brand = brand
self.model = model
def start_engine(self):
print(f"{self.brand} {self.model} engine started.")
Inheritance Example
# Parent class
class Animal:
def speak(self):
print("Animal makes a sound.")
# Child class inheriting from Animal
class Dog(Animal):
def speak(self):
print("Dog barks.")
# Creating instances
animal = Animal()
dog = Dog()
# Calling the method
animal.speak() # Output: Animal makes a sound.
dog.speak() # Output: Dog barks
Polymorphism Example
class Animal:
def sound(self):
pass
class Dog(Animal):
def sound(self):
return "Bark"
class Cat(Animal):
def sound(self):
return "Meow"
animals = [Dog(), Cat()]
for animal in animals:
print(animal.sound())
Advantages of OOP
• Code reusability
• Improved data organization
• Easier maintenance
• Flexibility through inheritance and polymorphism
Python Data Types and Comprehensions
1. Strings
Creation
s1 = "Hello"
s2 = 'World'
s3 = '''This is a multi-line
Access
• Individual characters: s[0] (first character)
• Slicing: s[start:end] (from start to end-1)
Example:
print(s1[1]) # 'e'
print(s1[0:3]) # ' Hel'
Functions
• len(s) – length of string
• s.lower(), s.upper(), s.strip(), s.replace(), s.find(), s.split(), s.join()
Key points
• Immutable
• String formatting: f-strings (f"Hello {name}")
• Escape characters: \n,( \n – New Line) ,\t(\t – Horizontal Tab), \\(\\ – Backslash), etc.
2. Lists
Creation
lst = [1, 2, 3, 4, 5]
nested_lst = [1, "text", [2, 3]]
Access
• Index: lst[0]
• Slicing: lst[start:end]
Example:
print(lst[2]) #3
print(lst[1:3]) # [2, 3]
Functions
• append(), extend(), insert(), remove(), pop(), clear(), index(), count(), sort(), reverse()
Key points
• Mutable
• Can hold different data types
3. Tuples
Creation
t1 = (1, 2, 3)
t2 = 3, 4, 5 # parentheses optional
single_element = (5,) # note the comma
Access
• Similar to lists: t[0], t[start:end]
Functions
• count(), index()
• No methods to modify (immutable)
Key points
• Immutable
• Can be used as dictionary keys
• Often used for fixed collections
4. Dictionaries
Creation
d1 = {'name': 'Alice', 'age': 25}
d2 = dict([('name', 'Bob'), ('age', 30)])
Access
• By key: d['name']
• Using get(): d.get('name') (avoids key errors)
Functions
• keys(), values(), items(), pop(), popitem(), update(), clear(), del d[key]
Key points
• Mutable
• Unordered (Python 3.7+ dictionaries maintain insertion order)
• Keys must be immutable types
5. Sets
Creation
s1 = {1, 2, 3}
s2 = set([4, 5, 6])
Access
• No indexing, but supports operations like union, intersection
s.union(s2), s.intersection(s2)
Functions
• add(), remove(), discard(), pop(), clear()
• Set operations: union(), intersection(), difference(), symmetric_difference()
Key points
• Unordered, no duplicates
• Use for set operations
6. Comprehensions
List Comprehensions
• Syntax:
[expression for item in iterable if condition]
Example:
python
squares = [x**2 for x in range(10) if x % 2 == 0]
Dictionary Comprehensions
• Syntax:
{key: value for item in iterable}
• Example:
square_dict = {x: x**2 for x in range(5)}
Set Comprehensions
• Syntax:
{expression for item in iterable}
• Example:
s = {x for x in range(10) if x % 2 == 0}
Numpy
NumPy (Numerical Python) is a fundamental package for scientific computing in Python.
• It provides support for large multi-dimensional arrays and matrices, along with a
collection of mathematical functions to operate on these arrays.
Key features of NumPy:
1. N-dimensional array:
• Core object fro holding high data(1D,2D,or multi-dimensional arrays).
• Faster and more memory-efficent than python lists.
2. Mathematical operations:
• Perform operations like addition ,subtraction, multiplication,division,etc.directly on
arrays.
3. Broadcasting:
• Automatically expands smaller arrays during operations without copying data
4. Linear algebra support:
• Includes functions like matrix multiplication. Inverse,eigenvalues,etc.
5. Random number generation:
• Tools for creating random numbers ,useful in simulations and ML
6. Integration with other libraries:
• Used as base by libraries like Pandas, Scikit_learn Tensorflow and OpenCv.
• As python lists would work as same but it is slower compared to numPy array
• Memory usage is more for lists then numpy arrray.
• Multi dimensional is not easy in lists as of numpy array is of built-in support
Arrays in Numpy
• Array in Numpy is a table of elements (usually numbers), all of the same type, indexed
by a tuple of positive integers.
• In Numpy, number of dimensions of the array is called rank of the array.
• A tuple of integers giving the size of the array along each dimension is known as shape of
the array.
• An array class in Numpy is called as ndarray.
• Elements in Numpy arrays are accessed by using square brackets and can be initialized
by using nested Python Lists.
Importing NumPy
import numpy as np
Creating a Numpy Array
import numpy as np
# Creating a rank 1 Array
arr = np.array([1, 2, 3])
print(arr)
# Creating a rank 2 Array
arr = np.array([[1, 2, 3],
[4, 5, 6]])
print(arr)
# Creating an array from tuple
arr = np.array((1, 3, 2))
print(arr)
• np.array() converts list or tuple-like structures into NumPy arrays.
• The shape of the arrays depends on the structure passed:
o [1, 2, 3] results in a 1D array of length 3.
o [[1, 2, 3], [4, 5, 6]] results in a 2D array with shape (2, 3).
o (1, 3, 2) tuple results in a 1D array of length 3.
• array Index
othe array index can be done in multiple ways. To print a range of an array, slicing
is done. Slicing of an array is defining a range in a new array which is used to
print a range of elements from the original array.
Example
import numpy as np
arr = np.array([[-1, 2, 0, 4],
[4, -0.5, 6, 0],
[2.6, 0, 7, 8],
[3, -7, 4, 2.0]])
# Printing a range of Array
# with the use of slicing method
arr2 = arr[:2, ::2]
print ("first 2 rows and alternate columns(0 and 2):\n", arr2)
# Printing elements at
# specific Indices
arr3 = arr[[1, 1, 0, 3],
[3, 2, 1, 0]]
print ("\nElements at indices (1, 3), "
"(1, 2), (0, 1), (3, 0):\n", arr3)
Output:
first 2 rows and alternate columns(0 and 2):
[[-1. 0.]
[ 4. 6.]]
Elements at indices (1, 3), (1, 2), (0, 1), (3, 0):
[0. 6. 2. 3.]
NumPy Basic Operations
o operations in NumPy allow you to perform mathematical operations on each
element of an array individually.
o We can perform arithmetic operations like addition, subtraction, multiplication,
and division directly on NumPy arrays.
import numpy as np
x = np.array([1, 2, 3])
y = np.array([4, 5, 6])
add = x + y
print("Addition:",add)
subtract = x - y
print("substration:",subtract)
multiply = x * y
print("multiplication:",multiply)
divide = x / y
print("division:", divide)
Addition: [5 7 9]
substration: [-3 -3 -3]
multiplication: [ 4 10 18]
division: [0.25 0.4 0.5 ]
Sorting Arrays
import numpy as np
# set alias names for dtypes
dtypes = [('name', 'S10'), ('grad_year', int), ('cgpa', float)]
# Values to be put in array
values = [('Hrithik', 2009, 8.5), ('Ajay', 2008, 8.7),
('Pankaj', 2008, 7.9), ('Aakash', 2009, 9.0)]
# Creating array
arr = np.array(values, dtype = dtypes)
print ( np.sort(arr, order = 'name'))
Data Structures in Pandas
Pandas is a popular Python library for data analysis. It simplifies working with structured data
through powerful data structures and tools for cleaning, processing, and analyzing data
efficiently.
Series
• A Series in pandas is a one-dimensional array-like object capable of holding various data
types, including integers, strings, and Python objects.
• It is defined by input data, an optional index for labeling the axes, an optional data type,
an optional name, and a copy parameter.
• The function returns a pandas Series object comprised of the provided data and its
associated index.
Syntax
pandas.Series(data=None, index=None, dtype=None, name=None,
copy=False)
import pandas as pd
a = ['g', 'e', 'e', 'k', 's']
res = pd.Series(a)
print(res)
Dataframe
A DataFrame is a two-dimensional, size-mutable and heterogeneous tabular data structure with
labeled rows and columns, SQL table.
Syntax:
pandas.DataFrame(data=None, index=None, columns=None, dtype=None, copy=False)
a={
'Name': ['Tom', 'Nick', 'Krish', 'Jack'],
'Age': [20, 21, 19, 18]
}
res = pd.DataFrame(a)
print(res)