Python Programming: Unit 5
Python Programming: Unit 5
Python Programming
Unit 5
Topics to be covered
Object Oriented Programming OOP in Python: Classes, 'self variable', Methods, Constructor
Method, Inheritance, Overriding Methods, Datahiding.
Error and Exceptions: Difference between an error and Exception, Handling Exception, try
except block, Raising Exceptions, User Defined Exceptions
OOP Principles
The four major principles of object oriented programming they are:
Encapsulation
Data Abstraction
Polymorphism
Inheritance
Encapsulation – It is the process of wrapping or binding the data and member function into a
single unit.
Data Abstraction – Data Abstraction is a process of hiding the implementation details from the
user, only the functionality will be provided to the user. This can be achieved by making the data
as private or protected.
Polymorphism - The assignment of more than one behavior to a particular function. The
operation performed varies by the types of objects or arguments involved.
Inheritance - The process of acquiring the properties or members of one class to another class.
1 | Page
Python Programming-5th Unit
Class
It is a user-defined prototype for an object that defines a set of attributes that characterize any
object of the class. The attributes are data members (class variables and instance variables) and
methods, accessed via dot notation.
In Python, everything is an object or an instance of the some class. In general, the class
can be defined as follow:
It is a Prototype from which objects are created.
It is a Model from which objects are created.
It is a Blueprint from which objects are created.
It is a Template from which objects are created.
Where class is the keyword, Employee is the class name. The class header contains class
keyword, class name and colon (:) operator. The class body contains class variables, data
members and member functions.
2 | Page
Python Programming-5th Unit
The “ init ” method has one argument “self” and every method has at least one
argument that “self”. This „self‟ argument is a reference to the current object on which the
method is being called. This “ init ” method is called with the help of class constructor.
We can add any number of functions or methods to the class as we like. The function that is
written inside the class is called “member function or method”. Writing the method is quite
similar to the ordinary function with just one difference. The methods must have one argument
named as “self”. This is the first argument that added to the beginning of parameters list. The
method or function definition is written inside the class as shown in the syntax:
#Defining class
class Employee: # class header
#declaring the class variable
count=0
#defining the constructor
def init (self,n,s):
self.name=n
self.sal=s
Employee.count+=1
#adding the method to the class
def dispemp(self):
print("The employee name is:",self.name,"Salary is:",self.sal)
self variable
The self argument refers to the current object.
Python takes care of passing the current object as argument to the method while calling.
3 | Page
Python Programming-5th Unit
Even if the method does not contain the argument, Python passes this “current object”
that called the method as argument, which in turn is assigned to the self variable in the
method definition.
Similarly a method defined to take one argument will actually take two arguments: self
and parameter.
#defining class and creating the object
class ABC:
def init (self,b):
self.balance=b
def disp(self): # method with self argument
print("The amount is:",self.balance)
ob=ABC(1000);
ob.disp() //method is called without argument, python passes „ob‟ as argument at the
background.
Output:
self.sal=s
Employee.count+=1
def dispemp(self):
print(" the name is:",self.name,"sal is :",self.sal)
#end of the class
#creating object
emp1=Employee("RAM",30000)
emp2=Employee("RAJU",40000)
#access the member function
emp1.dispemp()
emp2.dispemp()
print("The Number of employees are:",Employee.count)
Output:
5 | Page
Python Programming-5th Unit
Output:
Output:
Inheritance
Inheritance is the one of the most and essential concept of the Object
Oriented Programming. It is the process by which one class acquires the
properties from one or more classes. Here the properties are the Data
members
6 | Page and member functions. The new classes are created from the
existing classes. The newly created class is called "Derived" class. The
Python Programming-5th Unit
existing class is called "Base" class. The Derived class also called with other names such as sub
class, child class and descendent. The existing class is also called with other names such as
super class, parent class and ancestor. The concept of inheritance therefore, frequently used to
implement is-a relationship. The relationship between base and derived class is called "Kind of
Relationship".
REUSABILITY
The main reason to go to the concept of the Inheritance is reusing the existing properties, which
is called reusability. The reusability permits us to get the properties from the previous classes.
We can also add the extra features to the existing class. This is possible by creating new class
from existing class. The new class will have its own features and features acquired from the base
class.
Note: The new class will have its own properties and properties acquired
from the base class.
The Syntax to inherit the properties from one class to another will be as follow:
class Derived_Class (Base_Class):
#body of the Derived_class
We can even write the base class name along with name of the module instead of writing it
again.
7 | Page
Python Programming-5th Unit
TYPES OF INHERITANCES
Python has various types of Inheritances. The Process of Inheritance can be either Simple or
complex. This depends on the following points:
The Number of base classes used in the inheritance.
Nested derivation
Based on the above points the inheritances are classified in to the six different types.
Single Inheritance
Multilevel Inheritance
Multiple Inheritance
Hierarchical Inheritance
Hybrid Inheritance
Multi-path Inheritance
Single Inheritance
When only one class is derived from a single base class, such derivation is
called single inheritance. It is the simplest form of Inheritance. The New
class is termed as "Derived" class and the existing class is called
"Base" class. The newly created class contains the entire characteristics
from its base class. The Example program is already is given above.
Multilevel Inheritance
8 | Page
Python Programming-5th Unit
The process of deriving a new class from a derived class is known as "Multilevel Inheritance".
The intermediate derived class is also known as middle base class. C is derived from B. The
class B is derived from A. Here B is called Intermediate base class. The series of classes A, B
and C is called "Inheritance Pathway".
Multiple Inheritances
When two or more base classes are used in the derivation of
new class, it is called "Multiple Inheritance". The derived
class C has all the properties of both class A and class B.
Example program on Multiple –Inheritance:
Multiple Inheritance Output
class A: Enter a value:23
def add(self,x,y): Enter b value:12
self.x=x The addition is: 35
self.y=y The subtraction is: 11
print("The addition The product is: 276
is:",self.x+self.y)
class B: #Single Inheritance
def sub(self,x,y):
self.x=x
self.y=y
9 | Page
Python Programming-5th Unit
print("The subtraction
is:",self.x-self.y)
#Multiple Inheritance
class C(A,B):
def mul(self,x,y):
self.x=x
self.y=y
print("The product
is:",self.x*self.y)
#read data into a and b
a=int(input("Enter a value:"))
b=int(input("Enter b value:"))
#create object from derived
object
ob=C()
ob.add(a,b)
ob.sub(a,b)
ob.mul(a,b)
Hierarchical Inheritance
The Process of splitting the base class into several sub
classes is called, "Hierarchical Inheritance". All the
sub classes have the same properties of those in base
class. Here The classes B and C acquire properties from
the class A.
Hybrid Inheritance
A Combination of two or more types of inheritances is
called "Hybrid Inheritance". Sometimes it is essential to
derive a class using more types of inheritance. Here There
are 4 classes A, B, C and D. The class B acquires the
properties from A, hence there exist a single inheritance.
Class D acquires properties from B (which is a derived
class) and C, hence uses multiple inheritance. Here two
different types of Inheritances used are: Single and
Multiple.
Example Program on Hybrid-Inheritance
Hybrid-Inheritance Output
#types of Inheritances Enter a value:12
class A: Enter b value:3
def add(self,x,y): The addition is: 15
self.x=x The subtraction is: 9
self.y=y The product is: 36
print("The addition is:",self.x+self.y) The division is: 4.0
class B(A): #Single Inheritance
def sub(self,x,y):
self.x=x
10 | Page
Python Programming-5th Unit
self.y=y
print("The subtraction is:",self.x-self.y)
class C:
def mul(self,x,y):
self.x=x
self.y=y
print("The product is:",self.x*self.y)
#Hybrid Inheritance
class D(B,C):
def div(self,x,y):
self.x=x
self.y=y
print("The division is:",self.x/self.y)
#read data into a and b
a=int(input("Enter a value:"))
b=int(input("Enter b value:"))
#create object from derived object
ob=D()
ob.add(a,b)
ob.sub(a,b)
ob.mul(a,b)
ob.div(a,b)
Multi-Path Inheritance
Deriving a class from two derived classes that are in turn
derived from the same base class is called “Multi-Path
Inheritance”. In this context the derived class has two
immediate base classes, which are derived from one base class,
there by forming the grandparent, parent and child
relationship. The derived class inherits the features from base
class (grandparent) via two separate paths. Therefore, the base
class is also known as the indirect base class.
Problem in Multi-Path Inheritance (Diamond Problem)
The derived class has the members of the base class twice, via
parent1 and parent 2. This results in ambiguity because a duplicate set of members is created.
This is avoided in python using the dynamic algorithm (C3 and MRO) linearizes the search order
in such as way that left-to-right ordering is specified to avoid duplication.
11 | Page
Python Programming-5th Unit
Inheritance Composition
A class Inherits properties from another class A class contains objects of different classes as data
members
The derived class may override base class The container class cannot override the base class
functions functions
The derived class may add data or functionality The container class cannot add anything to the
to the base class contained class
This represents a “is-a” relationship This represents “has-a” relationship
12 | Page
Python Programming-5th Unit
13 | Page
Python Programming-5th Unit
The statements that can raise the exception are placed inside the try block, and the code that
handles is placed inside except block. Here try and except are keywords. The syntax for try-
except can be as given bellow:
try:
Statements
except ExceptionName:
Statements
The try statement works as follows.
First, the try block (the statement(s) between the try and except keywords) is executed.
If no exception occurs, the except block is skipped and execution of the try statement is finished.
If an exception occurs during execution of the try block, the rest of the block is skipped. Then if
its type matches the exception named after the except keyword, the except block is executed, and
then execution continues after the try statement.
If an exception occurs which does not match the exception named in the except block, it is
passed on to outer try statements; if no handler is found, it is an unhandled exception and
execution stops with a message.
Example Program
Exception1.py Exception1.py
#program without exception handler x=int(input("Enter x value"))
x=int(input("Enter x value")) y=int(input("Enter y value"))
y=int(input("Enter y value")) print("The sum is:",x+y)
print("The sum is:",x+y) print("The suntraction is:",x-y)
print("The suntraction is:",x-y) try:
print("The quotient is:",x/y) print("The quotient is:",x/y)
print("The product is:",x*y) print("The remainder is:",x%y)
print("The remainder is:",x%y) except ZeroDivisionError:
print("The power of x^y si:",x**y) print("You should not divide number with zero")
#legal code
print("The product is:",x*y)
print("The power of x^y si:",x**y)
Output Output
Enter x value4 Enter x value4
Enter y value0 Enter y value0
The sum is: 4 The sum is: 4
The suntraction is: 4 The suntraction is: 4
Traceback (most recent call last): You should not divide number with zero
File "E:/python/exception1.py", line 5, in The product is: 0
<module> The power of x^y si: 1
print("The quotient is:",x/y)
ZeroDivisionError: division by zero
14 | Page
Python Programming-5th Unit
The Syntax for multiple except blocks for single try will be as follow:
try:
Operations are done in this block
except Exception1:
If exception is matched, this block will be executed.
except Exception2:
If exception is matched, this block will be executed.
else:
If there is no exception matched, this block will be executed.
Multexcept1.py output
#read the data Enter value of x:3
try: Enter value of y:2
x=int(input("Enter value of x:")) 4.5
y=int(input("Enter value of y:")) End of the program
print(x**2/y) >>>
except (ValueError,ZeroDivisionError,KeyboardInterrupt ): ======= RESTART:
print("Check before you enter values foer x and y. Y E:/python/multiexcep1.py
should not be zero") =======
print("End of the program") Enter value of x:4
Enter value of y:
Check before you enter values for x and
y. Y should not be zero
15 | Page
Python Programming-5th Unit
try:
statements
except Exception1:
statements
except Exception2:
statement
except:
execute this block, if an exception match is found
Example Program
Testexcept.py Output
#read the data Enter value of x:4
try: Enter value of y:
x=int(input("Enter value of x:")) Unexpected error ....Terminating the
y=int(input("Enter value of y:")) program:
print(x**2/y) End of the program
except (TypeError):
print("Choose the correct type of value:")
except (ZeroDivisionError):
print("The value of y should not be zero")
except:
print("Unexpected error ....Terminating the
program:")
print("End of the program")
16 | Page
Python Programming-5th Unit
Testexcept.py Output
try: Enter value of x:4
x=int(input("Enter value of x:")) Enter value of y:2
y=int(input("Enter value of y:")) 8.0
print(x**2/y) Program execution is successful....
except (TypeError): End of the program
print("Choose the correct type of value:")
except (ZeroDivisionError):
print("The value of y should not be zero")
except (ValueError):
print("Unexpected error ....Terminating the
program:")
else:
print("Program execution is successful ... ")
print("End of the program")
raise [exception-name]
Example Program:
Testexcept.py Output
try: Enter value of x:4
x=int(input("Enter value of x:")) Enter value of y:0
y=int(input("Enter value of y:")) The value of y should not be zero
print(x**2/y) End of the program
raise ZeroDivisionError
except:
print("The value of y should not be zero")
Funexcep.py Output
def division(num,deno): Enter x value:4
try: Enter y value:0
r=num/deno You cannot divide number by zero
print("The quotient is:",r) >>>
except ZeroDivisionError: ======= RESTART: E:/python/funexcep.py
print("You cannot divide number by zero") ========
#function call Enter x value:4
x=int(input("Enter x value:")) Enter y value:2
y=int(input("Enter y value:")) The quotient is: 2.0
division(x,y) >>>
17 | Page
Python Programming-5th Unit
Built-in Exceptions:
Exception Description
Exception Base class for all exceptions
StopIteration Generated when next() method does not point
to any object
SystemExit Raised by sys.exit() function
StandardError Base class for all built-in exceptions(except
StopIteration and SystemExit)
ArithmeticError Base class for mathematical errors
OverflowError Raised when maximum limit of the number is
exceeded
FloatingPointError Raised when floating point operations could
not performed
ZeroDivisionError Raised when number is divided by zero
AssertionError Raised when assert condition fails
AttributeError Raised when attribute reference is failed
EOFError Raised when end of the file is reached
ImportError Raised when import statement is failed
KeyboardInterrupt Raised when user interrupts the keyboard (pressing
ctrl+c)
IndexError Raised when index is not found
KeyError Raised when key is not found
NameError Raised when an identifier is not defined
SyntaxError Raised when rules of language are violated
ValueError Raised when arguments are invalid type
TypeError Raised when two or more data types are mixed
Python also allows you to create your own exceptions by deriving classes from the standard
built-in exceptions.
Here is an example related to Exception. Here, a class is created that is subclassed from
Exception. This is useful when you need to display more specific information when an exception
is caught.
In the try block, the user-defined exception is raised and caught in the except block. The variable
„e‟ is used to create an instance of the class Networkerror.
class NetworkError(Exception):
def init (self, arg):
self.name = arg
18 | Page
Python Programming-5th Unit
try:
raise NetworkError('Network Connection Failed')
except NetworkError as e:
print("The network error is:", e.name)
Output:
The network error is: Network Connection Failed
19 | Page