0% found this document useful (0 votes)
4 views43 pages

Python Unit 5

The document provides an overview of Object-Oriented Programming (OOP) concepts and data analysis using Python, covering topics such as class definitions, inheritance types, constructors, destructors, and access modifiers. It also introduces NumPy for data analysis, detailing array types, operations, and data type conversions. The content is intended for educational purposes, with a focus on enhancing students' understanding of Python programming and data science.

Uploaded by

eluriakshara
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views43 pages

Python Unit 5

The document provides an overview of Object-Oriented Programming (OOP) concepts and data analysis using Python, covering topics such as class definitions, inheritance types, constructors, destructors, and access modifiers. It also introduces NumPy for data analysis, detailing array types, operations, and data type conversions. The content is intended for educational purposes, with a focus on enhancing students' understanding of Python programming and data science.

Uploaded by

eluriakshara
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

NAYANI SATEESH REDDY

[Link]. (AMIE - CSE), [Link]. (CSE/WT) [Link].(CS) (Ph.D. – JNTUK)


UGC – NET (Computer Science & Applications)
SLET – TS&AP (Computer Science & Applications)

AICTE-NPTEL – Data Science Domain Certified Faculty.


Infosys-Campus Connect (“Bronze Level Partner Faculty”)

Disclaimer : All the contents presented in this PPT are based on resources available
on the internet. Original copyrights are reserved for the respective content
contributors on the internet. This Presentation is used for knowledge-sharing
purposes only and also for the benefit of the students
Unit V –Object-Oriented Programming and Data Analysis
with Python

OOP: Class Definitions, Object-Orientated concepts, Inheritance,


and its types, Shallow and Deep Copying, and regular expressions

Data Analysis with Python: Numpy - ndarray – Introduction,


creating ndarray, data types for ndarray, operations between arrays
and scalars, basic indexing, and slicing.
Object-oriented programming (OOP) is a method of
structuring a program by bundling related properties and
behaviors into individual objects.

The main concept of OOPs is to bind the data and the


functions that work on that together as a single unit so that
no other part of the code can access this data.
OOPs Concepts in Python
•Class
•Objects
•Polymorphism
•Encapsulation
•Inheritance
•Data Abstraction

[Link]
_Object_Oriented_Programming_Using_Python.pdf
What is Inheritance in Python?
Inheritance is the property of Python through which the object can
acquire all of a parent object's properties and behaviors. It is one of
the most important Features of Object Oriented Programming

The parent-child relationship, also known as the IS-A relationship,


is represented by inheritance. For Example, Children inherit some
parent's properties such as face cuts and height.
Single Inheritance
Single inheritance is one of the types of inheritance in Python,
where there is only one base class and one child class. It is the
inheritance type that is most frequently used.
Multiple Inheritance
Multiple inheritances are another types of inheritance in Python,
which refer to deriving a class from multiple base classes.
Multilevel Inheritance
When there are multiple levels of inheritance, the new derived
class receives an additional inheritance from both the base class
and the derived class. This type of inheritance in Python is
referred to as multilevel inheritance.
Multipath Inheritance
When a class is derived from two or more classes which
are derived from the same base class then such type
of inheritance is called multipath inheritance.
Hierarchical Inheritance
Hierarchical inheritance is the term used to describe situations
with multiple derived classes from a single base class.

Hybrid Inheritance
It combines multiple inheritances with multilevel inheritance. A
class can have two or more parent classes, but only one of them
can have derived classes.

[Link]
[Link]
[Link]
Constructors are generally used for instantiating an object. The
task of constructors is to initialize(assign values) to the data
members of the class when an object of the class is created.
In Python the __init__() method is called the constructor and is
always called when an object is created.

def __init__(self):
# body of the constructor

Types of constructors :
default constructor
def __init__(self):
[Link] = “Hello World !!“
parameterized constructor
def __init__(self, f, s):
[Link] = f
[Link] = s
Destructors are called when an object gets destroyed. In Python,
destructors are not needed as much as in C++ because Python has a
garbage collector that handles memory management automatically.

The __del__() method is a known as a destructor method in Python.


It is called when all references to the object have been deleted i.e
when an object is garbage collected.

def __del__(self):
# body of destructor

del obj
A Class in Python has three types of access modifiers:
•Public Access Modifier
•Protected Access Modifier
•Private Access Modifier

Access Modifier: Public


The members declared as Public are accessible from outside the
Class through an object of the class.

Access Modifier: Protected


The members declared as Protected are accessible from outside
the class but only in a class derived from it that is in the child or
subclass.

Access Modifier: Private


These members are only accessible from within the class. No
outside Access is allowed.
public Access Modifier
By default, all the variables and member functions of a class
are public in a python program.

protected Access Modifier


According to Python convention adding a prefix _(single
underscore) to a variable name makes it protected. No additional
keyword required.

private Access Modifier


While the addition of prefix __(double underscore) results in a
member variable or function becoming private.
In Python, Assignment statements do not copy objects, they create
bindings between a target and an object.

When we use the = operator, It only creates a new variable that


shares the reference of the original object.

In order to create “real copies” or “clones” of these objects, we can


use the copy module in Python.

Syntax of Deep copy


Syntax: [Link](x)

Syntax of Shallow copy


Syntax: [Link](x)
In order to make these copies, we use the copy module. The
copy() returns a shallow copy of the list, and deepcopy() returns
a deep copy of the list.

Both objects will have the same values but have different IDs.
import copy

li1 = [1, 2, [3, 5], 4] # initializing list 1


assigncopy=li1 # Copy Through Assignment
print (“Original list ID:",id(li1), "Value: ", li1 )
print ("Copied list ID using =",id(assigncopy), "Value: ", assigncopy)
li2 = [Link](li1) # using shallow copy
print("shallow copy li2 ID: ", id(li2), "Value: ", li2)
li3 = [Link](li1) # using deep copy
print("deepcopyli3 ID: ", id(li3), "Value: ", li3)

Original list ID : 140075128304768 Value: [1, 2, [3, 5], 4]


Copied list ID using = 140075128304768 Value: [1, 2, [3, 5], 4]

shallow copy li2 ID: 140075128304704 Value: [1, 2, [3, 5], 4]


deepcopyli3 ID: 140075128306752 Value: [1, 2, [3, 5], 4]
import copy

li1 = [1, 2, [3,5], 4] # initializing list 1


li2 = [Link](li1) # using copy to shallow copy
li2[2][0]=7
print("After Shallow Copy::Old List" , li1)
print("After Shallow Copy::New List" , li2)
print()

li1 = [1, 2, [3,5], 4] # initializing list 1


li2 = [Link](li1) # using copy to deep copy
li2[2][0]=7
print("After Deep Copy::Old List" , li1)
print("After Deep Copy::New List" , li2)
After Shallow Copy::Old List [1, 2, [7, 5], 4]
After Shallow Copy::New List [1, 2, [7, 5], 4]

After Deep Copy::Old List [1, 2, [3, 5], 4]


After Deep Copy::New List [1, 2, [7, 5], 4]
NumPy

NumPy aims to provide an array object that is up to 50x faster


than traditional Python lists. The array object in NumPy is called
ndarray , it provides a lot of supporting functions that make
working with ndarray very easy. Arrays are very frequently used
in data science, where speed and resources are very important.

We need to import numpy in order to work with ndarrays.

import numpy
import numpy as np

l1=[1,2,3,4,5]
arr = [Link]([1,2,3,4,5])

print(type(l1)) #<class 'list'>


print(arr) #[1 2 3 4 5]

print(type(arr)) #<class '[Link]'>


0-D Arrays : 0-D arrays, or Scalars, are the elements in an array.
Each value in an array is a 0-D array.
arr = [Link](42)

1-D Arrays : An array that has 0-D arrays as its elements is called
uni-dimensional or 1-D array.
These are the most common and basic arrays.
arr = [Link]([1, 2, 3, 4, 5])

2-D Arrays : An array that has 1-D arrays as its elements is called a
2-D array. These are often used to represent matrix or 2nd order
tensors.
arr = [Link]([[1, 2, 3], [4, 5, 6]])

3-D arrays : An array that has 2-D arrays (matrices) as its elements is
called 3-D array. These are often used to represent a 3rd order tensor.
arr = [Link]([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]])
import numpy as np

array1=[Link]([1,2,3,4])
array2=[Link](10)
array3=[Link](range(1,10))
array4=[Link]([[1,2,3,4],[5,6,7,8]])
array5=[Link](4,2)

L1=list(map(int,input("enter elements").split(' ')))


array6=[Link](L1)

print("\narray1=",array1)
print("\narray2=",array2) print("\[Link]=",[Link])
print("\narray3=",array3) print("\[Link]=",[Link])
print("\narray4=",array4) print("\[Link]=",[Link])
print("\narray5=",array5)
print("\narray6=",array6)
O/P
array1= [1 2 3 4]

array2= [0 1 2 3 4 5 6 7 8 9]

array3= [1 2 3 4 5 6 7 8 9]

array4= [[1 2 3 4]
[5 6 7 8]]

array5= [[1 2]
[3 4]
[5 6]
[7 8]]

enter elements 1 2 3 4 5 6
array6= [1 2 3 4 5 6]

[Link]= 2

[Link]= (4, 2)

[Link]= 8
import numpy as np

a = [Link](42)
b = [Link]([1,2,3,4,5])
c = [Link]([[1,2,3], [4,5,6]])
d = [Link]([[[1,2,3], [4,5,6]], [[1,2,3], [4,5,6]]])

print("\na= ",a)
print("\nb= ",b)
print("\nc= ",c)
print("\nd= ",d)

print("\[Link]= ",[Link])
print("\[Link]= ",[Link])
print("\[Link]= ",[Link])
print("\[Link]= ",[Link])
O/P
a= 42

b= [1 2 3 4 5]

c= [[1 2 3]
[4 5 6]]

d= [ [ [1 2 3] [4 5 6] ]
[ [1 2 3] [4 5 6] ] ]

[Link]= 0
[Link]= 1
[Link]= 2
[Link]= 3
Data Types in NumPy
NumPy has some extra data types, and refer to data types

Below is a list of all data types in NumPy and the characters used to
represent them. import numpy as np
•i - integer
•b - boolean arr1 = [Link]([1,2,3,4],dtype='S')
•u - unsigned integer arr2 = [Link]([1,2,3,4],dtype='i')
•f - float arr3 = [Link]([1,2,3,4],dtype='f')
•c - complex float print("\narr1=",arr1)
•m - timedelta print("\narr2=",arr2)
•M - datetime print("\narr3=",arr3)
•O - object
•S - string O/P
•U - unicode string arr1= [b'1' b'2' b'3' b'4']
•V - fixed chunk of memory arr2= [1 2 3 4]
for other type ( void ) arr3= [1. 2. 3. 4.]
Converting Data Type on Existing Arrays

The best way to change the data type of an existing array, is to


make a copy of the array with the astype() method.

The astype() function creates a copy of the array, and allows you to
specify the data type as a parameter.
print(arr1,newarr1)
import numpy as print(arr2,newarr2)
nparr1 = [Link]([1.1,2.1,3.1]) print(arr3,newarr3)
newarr1 = [Link]('i') O/P
[1.1 2.1 3.1] => [1 2 3]
arr2 = [Link]([1.1,2.1,3.1]) [1.1 2.1 3.1] => [1 2 3]
newarr2 = [Link](int) [1 0 3]=> [ True False True]
arr3 = [Link]([1,0,3])
newarr3 = [Link](bool)
Scalar operations on Numpy arrays

Scalar operations on Numpy arrays include performing addition


or subtraction, or multiplication on each element of a Numpy
array.

import numpy as np
n1= [Link]([15, 20, 25, 30]) print("\nOriginal:",n1)
a1= n1 + 5 print("\n+5:",a1)
a2= n1 - 5 print("\n-5:",a2)
a3= n1 * 5 print("\n*5:",a3)
a4= n1 / 5 print("\n/5:",a4)
a5 = n1 %5 print("\n%5:",a5)
a6 = n1 ** 5 print("\n**5:",a6)
O/P
Original: [15 20 25 30]
+5: [20 25 30 35]
-5: [10 15 20 25]
*5: [ 75 100 125 150]
/5: [3. 4. 5. 6.]
%5: [0 0 0 0]
**5: [ 759375 3200000 9765625 24300000]
import numpy as np
a = [Link]([1, 2, 3])
b = [Link]([4, 5, 6])
print(a + b)
print(a - b)
print(a * b)
print(a / b)
print(a % b)
print(a ** b)

#Element wise operations will be done


O/P
[5 7 9]
[-3 -3 -3]
[ 4 10 18]
[0.25 0.4 0.5 ]
[1 2 3]
[ 1 32 729]
import numpy as np

#Dot Product & Cross Product


a = [Link]([1, 2, 3])
b = [Link]([4, 5, 6])
print(“Dot Product”,[Link](a,b))
print(“Cross Product”,[Link](a, b))

O/P
Dot Product 32
Cross Product [-3 6 -3]
a = [Link]([1, 2, 3])
[Link](a) # [ 2.71828183 7.3890561 20.08553692]

NumPy has standard trigonometry functions operate on arrays.

[Link]() ,[Link]() ,[Link]()


[Link]() ,[Link]() , [Link]()

a = [Link]([0,3.14/6,3.14/4,3.14/3,3.14/2])
print([Link](a)) [0. 0.4997701 0.70682518 0.86575984 0.99999968]
a = [Link]([0,90, 180, 270])
np.deg2rad(a)
a = [Link]([1, 2, 3])

print([Link](a)) #6
print([Link](a)) #1
print([Link](a)) #3

[Link]
[Link]
[Link]
Basic indexing, and slicing
[Link]

Basic indexing:

Indexing Using Index Arrays

import numpy as np
arr=[Link](1,10,2)
print("Elements of array: ",arr)
arr1=arr[[Link]([4,0,2,-1,-2])]
print("Indexed Elements of array arr: ",arr1)

O/P
Elements of array: [1 3 5 7 9]
Indexed Elements of array arr: [9 1 5 9 7]
Basic indexing, and slicing

Indexing in 1 dimension

import numpy as np
arr1=[Link](4)
print("Array arr1:",arr1)
print("Element at index 0 of arr1 is:",arr1[0])
print("Element at index 1 of arr1 is:",arr1[1])

O/P
Array arr1: [0 1 2 3]
Element at index 0 of arr1 is: 0
Element at index 1 of arr1 is: 1
Indexing in 2 Dimensions

arr=[Link](12)
arr1=[Link](3,4)
print("Array arr1:\n",arr1)
print("Element at 0th row and 0th column of arr1 is:",arr1[0,0])
print("Element at 1st row and 2nd column of arr1 is:",arr1[1,2])

O/P
Array arr1:
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
Element at 0th row and 0th column of arr1 is: 0
Element at 1st row and 2nd column of arr1 is: 6
Picking a Row or Column in 2-D NumPy Array

import numpy as np
arr=[Link](12)
arr1=[Link](3,4)
print("Array arr1:\n",arr1)
print("\n")
print("1st row :\n",arr1[1])

O/P
Array arr1:
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]

1st row :
[4 5 6 7]
Indexing in 3 Dimensions

import numpy as np
arr=[Link](12)
arr1=[Link](2,2,3)
print("Array arr1:\n",arr1)
print("Element:",arr1[1,0,2])

O/P
Array arr1:
[[[ 0 1 2]
[ 3 4 5]]

[[ 6 7 8]
[ 9 10 11]]]
Element: 8
Picking a Row or Column in a 3D Array

import numpy as np
arr=[Link](12)
arr1=[Link](2,2,3)
print("Array arr1:\n",arr1)
print("1st row :",arr1[0,1])

O/P

Array arr1:
[[[ 0 1 2]
[ 3 4 5]]

[[ 6 7 8]
[ 9 10 11]]]
1st row : [3 4 5]
Picking a matrix in a 3D array

import numpy as np
arr=[Link](12)
arr1=[Link](2,2,3)
print("Array arr1:\n",arr1)
print("\n")
print("1st matrix :\n",arr1[1])

O/P

Array arr1:
[[[ 0 1 2] 1st matrix :
[ 3 4 5]] [[ 6 7 8]
[[ 6 7 8] [ 9 10 11]]
[ 9 10 11]]]
Basic Slicing

import numpy as np
arr = [Link](12)
print(arr)
print("Element at index 6 of an array arr:",arr[6])
print("Element from index 3 to 8 of an array arr:",arr[3:8])

O/P

[ 0 1 2 3 4 5 6 7 8 9 10 11]
Element at index 6 of an array arr: 6
Element from index 3 to 8 of an array arr: [3 4 5 6 7]
import numpy as np
arr = [Link]([[[1,2,3],[3,4,5]],[[5,6,7],[9,10,11]]])
print ("The array is:")
print (arr )
print ('\n')

## Access the last dimension


print("using simple indexing:\n",arr[:,:,0])
print("using ellipsis:\n ",arr[...,0])

O/P
The array is : using simple indexing:
[[[ 1 2 3] [[1 3]
[ 3 4 5]] [5 9]]
using ellipsis:
[[ 5 6 7] [[1 3]
[ 9 10 11]]] [5 9]]
mport NumPy as np

arr = [Link]([[11 ,12 ],[13 ,14 ],[15 ,16 ]])


print(arr[[0 ,1 ,2 ],[0 ,0 ,1]])

O/P

[11 13 16]
import numpy as np
arr=[Link]([2,76,34,12,90,32])
print("Original array: ",arr)
print("Advanced array :",arr[[1,3,4]])

O/P
Original array: [ 2 76 34 12 90 32]
Advanced array : [76 12 90]
Boolean Indexing

import numpy as np
arr = [Link]([11,6,41,10,29,50,55,45])
print(arr[arr>35])

O/P
[41 50 55 45]
Reference:

[Link]
_Object_Oriented_Programming_Using_Python.pdf

[Link]

[Link]

[Link]

[Link]

[Link]

[Link]

[Link]

You might also like