Python Week-6
Python Week-6
Department of CSE
CRT
Python Programming
Week-6
Topics:
Inheritance
Method Overriding
Exception Handling
User Defined Exception
Inheritance:
• The technique of creating a new class from an existing class in order to access all the
properties is called Inheritance.
• The old or existing class is called the Base class or Super class and the new class is
known as the Derived class or Sub-class.
• The derived classes are created by first inheriting the data and methods of the base
class and then adding new specialized data and methods in it.
• In this process of inheritance, the base class remains unchanged.
• The concept of inheritance is used to implement the is-a relationship.
• For example, teacher IS-A person, student IS-A person; while both teacher and
student are a person in the first place, both also have some distinguishing features.
• So all the common traits of teacher and student are specified in the Person class and
specialized features are incorporate in two separate classes- Teacher and Student.
Types of Inheritance:
• Single Inheritance
• Multiple Inheritance
• Multilevel inheritance
• Hierarchical Inheritance
Single Inheritance
• When a single class is derived from one base class, it is called Single Inheritance.
• The derived class has all the features of base class and in addition to them can have
additional new features.
•
The syntax for multiple inheritance(assume there are 2 base classes):
class FirstBaseClassName:
statement block
class SecondBaseClassName:
statement block
class DerivedClassName (FirstBaseClassName, SecondBaseClassName):
statement block
Program:
class State:
state="Andhra Pradesh"
def stateShow(self):
print("State:",self.state)
class City:
city="Vizag"
def cityShow(self):
print("City:",self.city)
class College(State,City):
college="REC"
def collegeShow(self):
print("College:",self.college)
clgObj=College()
clgObj.collegeShow()
clgObj.cityShow()
clgObj.stateShow()
Output:
College: REC
City: Vizag
State: Andhra Pradesh
Multilevel Inheritance
• The technique of deriving a class from an already derived class is called Multi-level
Inheritance.
Now, the question arises in what order the classes will be searched - breath-first or depth-
first. By default, Python goes with the depth-first.
That’s is why in the diagram the Python searches the dothis() method first in class A. So the
method resolution order in the below example will be D→B→A→C
Example:
class A:
def dothis(self):
print("In A")
class B(A):
pass
class C:
def dothis(self):
print("In C")
class D(B,C):
pass
d=D()
d.dothis()
Output:
In A
Example:
class A:
def do(self):
print("In A")
class B(A):
pass
class C:
def dothis(self):
print("In C")
class D(B,C):
pass
d=D()
d.dothis()
Output:
In C
Above diagram will be considered ambiguous. From our previous example understanding
“Method Resolution Order” .i.e. MRO will be D→B→A→C→A but it’s not. On getting the
second A from the C, Python will ignore the previous A. so the MRO will be in this case will
be D→B→C→A.
Simple rule to understand this scenario is- if the same class appear in the method resolution
order, the earlier appearances of this class will be remove from the method resolution order.
Example:
class A:
def dothis(self):
print("In A")
class B(A):
pass
class C(A):
def dothis(self):
print("In C")
class D(B,C):
pass
d=D()
d.dothis()
Output:
In C
Hierarchical Inheritance
• The process of deriving more than one class from a single base class is called
Hierarchical Inheritance.
1. Built-in Exceptions
2. User-defined Exceptions
Built-in Exceptions:
Built-in exceptions are the exceptions which are available in Python library.
Python has many built-in exceptions which forces your program to output an error when
something in it goes wrong.
When these exceptions occur, it causes the current process to stop and passes it to the calling
process until it is handled. If not handled, our program will crash.
These built-in exceptions can be viewed using the local() built-in functions as follows :
dir(locals()['__builtins__'])
Most frequently raised built-in exceptions:
KeyboardInterrupt Raised when the user hits interrupt key (Ctrl+c or delete).
Exception Handling:
try block:
The programmer should observe the statements in his program where there may be a
possibility of exception. Such statements to be written inside a try block.
except block:
The programmer should write the except block where the exception need to be handled.
Here, the programmer can also display exception details and a message regarding what can
be done to avoid the error.
The try-except blocks looks like as,
Program:
x=20
y=0
try:
z=x/y
print("Result:",z)
except ZeroDivisionError:
print("Division with zero is not possible!")
Output:
Division with zero is not possible!
Multiple Except Blocks:
Python allows you to have multiple except blocks for a single try block.
The block which matches with the exception generated will get executed.
The try ... except block can optionally have an else clause.
The statement(s) in the else block is executed only if the try clause does not raise an
exception.
Program:
try:
num=int(input())
square=num**2
except KeyboardInterrupt:
print("Nothing is given as input..Terminated!")
except ValueError:
print("You should have given a number..Terminated!")
else:
print("Square value:",square)
Sample Input: abc
Sample output: You should have given a number..Terminated!
Sample Input: 3
Sample output: Square value: 9
finally block:
Program:
x=20
y=int(input())
try:
z=x/y
print("Result:",z)
except ZeroDivisionError:
print("Division with zero is not possible!")
finally:
print("Finished..closing..")
Input: 0
Output: Division with zero is not possible!
Finished..closing..
Input: 5
Output: Result: 4.0
Finished..closing..
except: block without Exception:
Program:
try:
print(a)
except Exception:
print("Unknown defined exception..")
Output:
Unknown defined exception..
Raising Exceptions:
Program:
try:
raise Exception("Raised","Intentionally")
except Exception as exObj:
print(exObj.args)
Output:
('Raised', 'Intentionally')
User-defined Exceptions:
Program:
#class MyException is derived from super class Exception
class MyException(Exception):
# Constructor or Initializer
def __init__(self, value):
self.value = value
# __str__ is to print() the value
def __str__(self):
return(self.value)
try:
raise MyException("It is my own exception")
except MyException as myExObj:
print(myExObj)
Output:
It is my own exception
MCQs
testmoz.com/9429198-OOPs-II