Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
8 views

Unit - II Python

Uploaded by

prasannadp04
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Unit - II Python

Uploaded by

prasannadp04
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 27

Python for Data Science

UNIT II
User defined Modules and Packages in Python- Files: File manipulations, File and
Directory related methods - Python Exception Handling. OOPs Concepts -Class
and Objects, Constructors – Data hiding- Data Abstraction-Inheritance.

Python Modules

Modules provide us with a way to share reusable functions. A module is


simply a “Python file” which contains code we can reuse in multiple Python
programs. A module may contain functions, classes, variables, lists, etc.

Modules in Python can be of two types:

 User-defined Modules.
 Built-in Modules.

User-Defined Modules

We can create our own functions and classes, put them inside modules. We
can now include hundreds of lines of code into any program just by writing a
simple import statement.

Create a simple Python module

Create a simple calc.py program in which we define two functions,


one add and another subtract.

# A simple module, calc.py


def add(x, y):
return (x+y)

def subtract(x, y):


return (x-y)

Import Module in Python

Unit - II Page 1
Python for Data Science

We can import the functions, and classes defined in a module to another


module using the import statement in some other Python source file.

Syntax of Python Import

import module

Importing modules in Python

Now, we are importing the calc that we created earlier to perform add
operation.
# importing module calc.py
import calc
print(calc.add(10, 2))

Built-in Modules in Python

Python comes with a “rich standard library”. This rich standard library
contains lots of built-in modules. We can import and use any of the built-in
modules.

# importing built-in module math


import math

# using square root(sqrt) function contained


# in math module
print(math.sqrt(25))

# using pi function contained in math module


print(math.pi)

# 2 radians = 114.59 degrees


print(math.degrees(2))

# 60 degrees = 1.04 radians

Unit - II Page 2
Python for Data Science

print(math.radians(60))

# Sine of 2 radians
print(math.sin(2))

# Cosine of 0.5 radians


print(math.cos(0.5))

# Tangent of 0.23 radians


print(math.tan(0.23))

# 1 * 2 * 3 * 4 = 24
print(math.factorial(4))

The from-import Statement in Python

Python’s from statement we can import specific attributes from a module


without importing the module as a whole.

Importing specific attributes from the module

Here, we are importing specific sqrt and factorial attributes from the math
module.

# importing sqrt() and factorial from the


# module math
from math import sqrt, factorial

# if we simply do "import math", then


# math.sqrt(16) and math.factorial()
# are required.
print(sqrt(16))
print(factorial(6))
Output:
4.0
720
Unit - II Page 3
Python for Data Science

Import all Names


The * symbol used with the from import statement is used to import all
the names from a module to a current namespace.
Syntax:

from module_name import *

The use of * has its advantages and disadvantages. If you know exactly
what you will be needing from the module, it is not recommended to use *, else
do so.
# importing sqrt() and factorial from the
# module math
from math import *

# if we simply do "import math", then


# math.sqrt(16) and math.factorial()
# are required.
print(sqrt(16))
print(factorial(6))
Output
4.0
720

Locating Python Modules

Whenever a module is imported in Python the interpreter looks for


several locations. First, it will check for the built-in module, if not found then it
looks for a list of directories defined in the sys.path. Python interpreter searches
for the module in the following manner –

 First, it searches for the module in the current directory.


 If the module is n’t found in the current directory, Python then searches each
directory in the shell variable PYTHONPATH. The PYTHONPATH is an
environment variable, consisting of a list of directories.

Unit - II Page 4
Python for Data Science

 If that also fails python checks the installation-dependent list of directories


configured at the time Python is installed.
Renaming the Python module
We can rename the module while importing it using the keyword.

Syntax: Import Module_name as Alias_name


# importing sqrt() and factorial from the
# module math
import math as mt

# if we simply do "import math", then


# math.sqrt(16) and math.factorial()
# are required.
print(mt.sqrt(16))
print(mt.factorial(6))
Output
4.0
720

PACKAGE

A Python module may contain several classes, functions, variables, etc.


whereas a Python package can contains several module. In simpler terms a
package is folder that contains various modules as files.

Creating Package
Create a package named mypckg that will contain two modules mod1 and
mod2. To create this module follow the below steps –

 Create a folder named mypckg.


 Inside this folder create an empty Python file i.e. __init__.py
 Then create two modules mod1 and mod2 in this folder.

mod1.py
def gfg():
print("Welcome to GFG")

Unit - II Page 5
Python for Data Science

mod2.py
def sum(a, b):
return a+b

The hierarchy of the our package looks like this –

mypckg
|
|
---__init__.py
|
|
---mod1.py
|
|
---mod2.py

Understanding __init__.py

__init__.py helps the Python interpreter to recognise the folder as


package. It also specifies the resources to be imported from the modules. If the
__init__.py is empty this means that all the functions of the modules will be
imported. We can also specify the functions from each module to be made
available.

Import Modules from a Package


We can import these modules using the from…import statement and the
dot(.) operator.
Syntax:
from package_name import module_name

Example: Import Module from package


We will import the modules from the above created package and will use
the functions inside those modules.

Unit - II Page 6
Python for Data Science

from mypckg import mod1


from mypckg import mod2

mod1.gfg()
res = mod2.sum(1, 2)
print(res)
Output:
Welcome to GFG
3

We can also import the specific function also using the same syntax.

Example: Import Specific function from the module


from mypckg.mod1 import gfg
from mypckg.mod2 import sum

gfg()
res = sum(1, 2)
print(res)
Output:
Welcome to GFG
3

EXCEPTION
Error in Python can be of two types i.e. Syntax errors and Exceptions .
Errors are the problems in a program due to which the program will stop the
execution. On the other hand, exceptions are raised when some internal events
occur which changes the normal flow of the program.

Difference between Syntax Error and Exceptions

Syntax Error
As the name suggests this error is caused by the wrong syntax in the
code. It leads to the termination of the program.

Unit - II Page 7
Python for Data Science

# initialize the amount variable


amount = 10000

# check that You are eligible to


# purchase Dsa Self Paced or not
if(amount > 2999)
print("You are eligible to purchase Dsa Self Paced")

Exceptions
Exceptions are raised when the program is syntactically correct, but the
code resulted in an error. This error does not stop the execution of the program,
however, it changes the normal flow of the program.

Example:
# initialize the amount variable
marks = 10000

# perform division with 0


a = marks / 0
print(a)

In the above example raised the ZeroDivisionError as we are trying to


divide a number by 0.

Try and Except Statement – Catching Exceptions

Try and except statements are used to catch and handle exceptions in
Python. Statements that can raise exceptions are kept inside the try clause and
the statements that handle the exception are written inside except clause.

Example
Let us try to access the array element whose index is out of bound and
handle the corresponding exception.
# Python program to handle simple runtime error

a = [1, 2, 3]

Unit - II Page 8
Python for Data Science

try:
print ("Second element =" a[1])

# Throws error since there are only 3 elements in array


print ("Fourth element = “ a[3])

except:
print ("An error occurred")

Output
Second element = 2
An error occurred

In the above example, the statements that can cause the error are placed
inside the try statement (second print statement in our case). The second print
statement tries to access the fourth element of the list which is not there and
this throws an exception. This exception is then caught by the except statement.

Catching Specific Exception

A try statement can have more than one except clause, to specify handlers
for different exceptions. Please note that at most one handler will be executed.
For example, we can add IndexError in the above code. The general syntax for
adding specific exceptions are –

try:
# statement(s)
except IndexError:
# statement(s)
except ValueError:
# statement(s)

Example: Catching specific exception in Python


# Program to handle multiple errors with one
# except statement

Unit - II Page 9
Python for Data Science

def fun(a):
if a < 4:

# throws ZeroDivisionError for a = 3

try:
fun(3)

# note that braces () are necessary here for


# multiple exceptions
except ZeroDivisionError:
print("ZeroDivisionError Occurred and Handled")

Output
ZeroDivisionError Occurred and Handled

Try with Else Clause


In python, you can also use the else clause on the try-except block which
must be present after all the except clauses. The code enters the else block only
if the try clause does not raise an exception.
Example: Try with else clause
# Program to depict else clause with try-except
# Function which returns a/b

def AbyB(a , b):


try:
c = ((a+b) / (a-b))
except ZeroDivisionError:
print ("a/b result in 0")
else:
print (c)

# Driver program to test above function


AbyB(2.0, 3.0)
AbyB(3.0, 3.0)
Output:
Unit - II Page 10
Python for Data Science

-5.0
a/b result in 0

Finally Keyword in Python


Python provides a keyword finally, which is always executed after the try
and except blocks. The final block always executes after normal termination of
try block or after try block terminates due to some exception.

Syntax:
try:
# Some Code....

except:
# optional block
# Handling of exception (if required)

else:
# execute if no exception

finally:
# Some code .....(always executed)
Example:
# Python program to demonstrate finally
# No exception Exception raised in try block

try:
k = 5//0 # raises divide by zero exception.
print(k)

# handles zerodivision exception


except ZeroDivisionError:
print("Can't divide by zero")

finally:
# this block is always executed
# regardless of exception generation.

Unit - II Page 11
Python for Data Science

print('This is always executed')


Output:
Can't divide by zero
This is always executed

Raising Exception
The raise statement allows the programmer to force a specific exception
to occur. The sole argument in raise indicates the exception to be raised. This
must be either an exception instance or an exception class (a class that derives
from Exception).
# Program to depict Raising Exception

try:
raise NameError("Hi there") # Raise Error
except NameError:
print ("An exception")
raise # To determine whether the exception was raised or not
The output of the above code will simply line printed as “An exception”
but a Runtime error will also occur in the last due to the raise statement in the
last line. So, the output on your command line will look like

Traceback (most recent call last):


File "/home/d6ec14ca595b97bff8d8034bbf212a9f.py", line 5, in <module>
raise NameError("Hi there") # Raise Error
NameError: Hi there

OBJECT ORIENTED PROGRAMMING

In Python, object-oriented Programming (OOPs) is a programming


paradigm that uses objects and classes in programming.

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.

Unit - II Page 12
Python for Data Science

Main Concepts of Object-Oriented Programming (OOPs)


 Class
 Objects
 Polymorphism
 Encapsulation
 Inheritance
 Data Abstraction

Class
A class is a collection of objects. A class contains the blueprints or the
prototype from which the objects are being created. It is a logical entity that
contains some attributes and methods.

 Classes are created by keyword class.


 Attributes are the variables that belong to a class.
 Attributes are always public and can be accessed using the dot (.)
operator. Eg.: Myclass.Myattribute

Class Definition Syntax:


class ClassName:
# Statement-1
.

Unit - II Page 13
Python for Data Science

.
.
# Statement-N

Object

The object is an entity that has state and behavior


Object has attributes and methods.
When we define a class, it needs to create an object to allocate the memory.

Consider the following example.


Example:

class car:
def __init__(self,modelname, year):
self.modelname = modelname
self.year = year
def display(self):
print(self.modelname,self.year)

c1 = car("Toyota", 2016)
c1.display()

Output:
Toyota 2016

In the above example, we have created the class named car, and it has two
attributes modelname and year. We have created a c1 object to access the class
attribute. The c1 object will allocate memory for these values.

The self

1. Class methods must have an extra first parameter in the method definition.
We do not give a value for this parameter when we call the method, Python
provides it
2. If we have a method that takes no arguments, then we still have to have one
argument.

Unit - II Page 14
Python for Data Science

3. When we call a method of this object as myobject.method(arg1, arg2), this is


automatically converted by Python into MyClass.method(myobject, arg1,
arg2)

The __init__ method (constructor)

The __init__ method is similar to constructors in C++ and Java. It is run as


soon as an object of a class is instantiated. The method is useful to initialization
of the object.

Now let us define a class and create some objects using the self and
__init__ method.

class Employee:
def __init__(self, name, id):
self.id = id
self.name = name

def display(self):
print(self.id, self.name)

emp1 = Employee("John", 101)


emp2 = Employee("David", 102)
emp1.display()
emp2.display()

The non-parameterized constructor uses when we do not want to


manipulate the value or the constructor that has only self as an argument.
Consider the following example.

Example

class Student:
# Constructor - non parameterized
def __init__(self):
print("This is non parametrized constructor")

def show(self,name):

Unit - II Page 15
Python for Data Science

print("Hello",name)

student = Student()
student.show("John")

Python Parameterized Constructor

The parameterized constructor has multiple parameters along with the self.
Consider the following example.

Example
class Student:
# Constructor - parameterized
def __init__(self, name):
print("This is parametrized constructor")
self.name = name

def show(self):
print("Hello",self.name)

student = Student("John")
student.show()

Python Default Constructor

When we do not include the constructor in the class or forget to declare it,
then that becomes the default constructor.

It does not perform any task but initializes the objects.


Consider the following example.

Example
class Student:
roll_num = 101
name = "Joseph"

def display(self):
Unit - II Page 16
Python for Data Science

print(self.roll_num,self.name)

st = Student()
st.display()

But a class can implement the special method __del__(), called a


destructor, that is invoked when the instance is about to be destroyed. This
method might be used to clean up any non memory resources used by an
instance.
Example
This __del__() destructor prints the class name of an instance that is about
to be destroyed −
class Point:
def __init__( self, x=0, y=0):
self.x = x
self.y = y
def __del__(self):
class_name = self.__class__.__name__
print 9class_name, "destroyed")

pt1 = Point()
pt2 = pt1
pt3 = pt1
print (id(pt1), id(pt2), id(pt3)) # prints the ids of the obejcts
del pt1
del pt2
del pt3
When the above code is executed, it produces following result −
3083401324 3083401324 3083401324
Point destroyed

Inheritance

Unit - II Page 17
Python for Data Science

Instead of starting from scratch, we can create a class by deriving it from a


preexisting class by listing the parent class in parentheses after the new class
name.
The child class inherits the attributes of its parent class, and you can use
those attributes as if they were defined in the child class. A child class can also
override data members and methods from the parent.
Syntax
Derived classes are declared much like their parent class; however, a list of
base classes to inherit from is given after the class name −
class SubClassName (ParentClass1[, ParentClass2, ...]):
'Optional class documentation string'
class_suite

Types of Inheritance in Python

Types of Inheritance depend upon the number of child and parent classes
involved. There are four types of inheritance in Python:

Single Inheritance:
Single inheritance enables a derived class to inherit properties from a
single parent class, thus enabling code reusability and the addition of new
features to existing code.

# Python program to demonstrate


Unit - II Page 18
Python for Data Science

# single inheritance

# Base class
class Parent:
def func1(self):
print("This function is in parent class.")

# Derived class
class Child(Parent):
def func2(self):
print("This function is in child class.")

# Driver's code
object = Child()
object.func1()
object.func2()

Multiple Inheritance:
When a class can be derived from more than one base class this type of
inheritance is called multiple inheritances. In multiple inheritances, all the
features of the base classes are inherited into the derived class.

# Python program to demonstrate


# multiple inheritance

# Base class1
class Mother:

Unit - II Page 19
Python for Data Science

mothername = ""
def mother(self):
print(self.mothername)

# Base class2
class Father:
fathername = ""
def father(self):
print(self.fathername)

# Derived class
class Son(Mother, Father):
def parents(self):
print("Father :", self.fathername)
print("Mother :", self.mothername)

# Driver's code
s1 = Son()
s1.fathername = "RAM"
s1.mothername = "SITA"
s1.parents()

Multilevel Inheritance :
In multilevel inheritance, features of the base class and the derived class
are further inherited into the new derived class. This is similar to a relationship
representing a child and a grandfather.

Unit - II Page 20
Python for Data Science

# Python program to demonstrate


# multilevel inheritance

# Base class
class Grandfather:
def __init__(self, grandfathername):
self.grandfathername = grandfathername

# Intermediate class
class Father(Grandfather):
def __init__(self, fathername, grandfathername):
self.fathername = fathername

# invoking constructor of Grandfather class


Grandfather.__init__(self, grandfathername)

# Derived class
class Son(Father):
def __init__(self, sonname, fathername, grandfathername):
self.sonname = sonname

# invoking constructor of Father class


Father.__init__(self, fathername, grandfathername)

def print_name(self):
print('Grandfather name :', self.grandfathername)
print("Father name :", self.fathername)
print("Son name :", self.sonname)

# Driver code
s1 = Son('Prince', 'Rampal', 'Lal mani')
print(s1.grandfathername)
s1.print_name()

Hierarchical Inheritance:

Unit - II Page 21
Python for Data Science

When more than one derived class 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.

# Python program to demonstrate


# Hierarchical inheritance

# Base class
class Parent:
def func1(self):
print("This function is in parent class.")

# Derived class1
class Child1(Parent):
def func2(self):
print("This function is in child 1.")

# Derivied class2
class Child2(Parent):
def func3(self):
print("This function is in child 2.")

# Driver's code
object1 = Child1()
object2 = Child2()
object1.func1()
object1.func2()

Unit - II Page 22
Python for Data Science

object2.func1()
object2.func3()

Hybrid Inheritance:
Inheritance consisting of multiple types of inheritance is called hybrid
inheritance.

# Python program to demonstrate


# hybrid inheritance

class School:
def func1(self):
print("This function is in school.")

class Student1(School):
def func2(self):
print("This function is in student 1. ")

class Student2(School):
def func3(self):
print("This function is in student 2.")

class Student3(Student1, School):


def func4(self):
print("This function is in student 3.")

# Driver's code
object = Student3()
object.func1()

Unit - II Page 23
Python for Data Science

object.func2()

Polymorphism

Overriding Methods

You can always override your parent class methods. One reason for
overriding parent's methods is because you may want special or different
functionality in your subclass.
Example

class Parent: # define parent class


def myMethod(self):
print 'Calling parent method'

class Child(Parent): # define child class


def myMethod(self):
print 'Calling child method'

c = Child() # instance of child


c.myMethod() # child calls overridden method

When the above code is executed, it produces the following result −


Calling child method

Encapsulation
Encapsulation is one of the fundamental concepts in object-oriented
programming (OOP). It describes the idea of wrapping data and the methods
that work on data within one unit.
This puts restrictions on accessing variables and methods directly and can
prevent the accidental modification of data. To prevent accidental change, an
object’s variable can only be changed by an object’s method.
Those types of variables are known as private variables.

Unit - II Page 24
Python for Data Science

A class is an example of encapsulation as it encapsulates all the data that


is member functions, variables, etc.

Protected members (in C++ and JAVA) are those members of the class that
cannot be accessed outside the class but can be accessed from within the class
and its subclasses. To accomplish this in Python, just follow the convention by
prefixing the name of the member by a single underscore “_”.

Although the protected variable can be accessed out of the class as well as
in the derived class (modified too in derived class), it is customary(convention
not a rule) to not access the protected out the class body.
Note: The __init__ method is a constructor and runs as soon as an object of a
class is instantiated.

# Python program to
# demonstrate protected members

# Creating a base class


class Base:
def __init__(self):
# Protected member
self._a = 2

# Creating a derived class


class Derived(Base):
def __init__(self):
# Calling constructor of
# Base class
Base.__init__(self)
print("Calling protected member of base class: ", self._a)
# Modify the protected variable:
Unit - II Page 25
Python for Data Science

self._a = 3
print("Calling modified protected member outside class: ", self._a)

obj1 = Derived()
obj2 = Base()

# Calling protected member


# Can be accessed but should not be done due to convention
print("Accessing protected member of obj1: ", obj1._a)

# Accessing the protected variable outside


print("Accessing protected member of obj2: ", obj2._a)

Output:
Calling protected member of base class: 2
Calling modified protected member outside class: 3
Accessing protected member of obj1: 3
Accessing protected member of obj2: 2

Private members
Private members are similar to protected members, the difference is that
the class members declared private should neither be accessed outside the class
nor by any base class. In Python, there is no existence of Private instance
variables that cannot be accessed except inside a class.

However, to define a private member prefix the member name with


double underscore “__”.

# Python program to
# demonstrate private members

# Creating a Base class


class Base:
def __init__(self):
self.a = "a is public"

Unit - II Page 26
Python for Data Science

self.__c = "c is private"

# Creating a derived class


class Derived(Base):
def __init__(self):

# Calling constructor of
# Base class
Base.__init__(self)
print("Calling private member of base class: ")
print(self.__c)

# Driver code
obj1 = Base()
print(obj1.a)
obj2 = Derived()
# will also raise an AtrributeError as
# private member of base class
# is called inside derived class

Data Abstraction

Data abstraction and encapsulation both are often used as synonyms. Both
are nearly synonyms because data abstraction is achieved through encapsulation.

Abstraction is used to hide internal details and show only functionalities.


Abstracting something means to give names to things so that the name captures
the core of what a function or a whole program does.

Unit - II Page 27

You might also like