Unit - II Python
Unit - II Python
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
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.
Unit - II Page 1
Python for Data Science
import module
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))
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.
Unit - II Page 2
Python for Data Science
print(math.radians(60))
# Sine of 2 radians
print(math.sin(2))
# 1 * 2 * 3 * 4 = 24
print(math.factorial(4))
Here, we are importing specific sqrt and factorial attributes from the math
module.
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 *
Unit - II Page 4
Python for Data Science
PACKAGE
Creating Package
Create a package named mypckg that will contain two modules mod1 and
mod2. To create this module follow the below steps –
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
mypckg
|
|
---__init__.py
|
|
---mod1.py
|
|
---mod2.py
Understanding __init__.py
Unit - II Page 6
Python for Data Science
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.
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.
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
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
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])
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.
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)
Unit - II Page 9
Python for Data Science
def fun(a):
if a < 4:
try:
fun(3)
Output
ZeroDivisionError Occurred and Handled
-5.0
a/b result in 0
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)
finally:
# this block is always executed
# regardless of exception generation.
Unit - II Page 11
Python for Data Science
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
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
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.
Unit - II Page 13
Python for Data Science
.
.
# Statement-N
Object
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
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)
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")
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()
When we do not include the constructor in the class or forget to declare it,
then that becomes the default constructor.
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()
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
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.
# 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.
# 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
# Base class
class Grandfather:
def __init__(self, grandfathername):
self.grandfathername = grandfathername
# Intermediate class
class Father(Grandfather):
def __init__(self, fathername, grandfathername):
self.fathername = fathername
# Derived class
class Son(Father):
def __init__(self, sonname, fathername, grandfathername):
self.sonname = sonname
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.
# 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.
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.")
# 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
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
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
self._a = 3
print("Calling modified protected member outside class: ", self._a)
obj1 = Derived()
obj2 = Base()
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.
# Python program to
# demonstrate private members
Unit - II Page 26
Python for Data Science
# 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.
Unit - II Page 27