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

Python Week-6

The document discusses various object-oriented programming concepts in Python like inheritance, method overriding, and exception handling. It provides examples to illustrate: 1. Inheritance allows a child class to inherit attributes and behaviors from a parent class. There are different types of inheritance like single, multiple, multilevel and hierarchical. 2. Method overriding allows a child class to provide a specific implementation of a method defined in the parent class. The super() method can call the parent method. 3. Exception handling allows programs to deal with runtime errors gracefully using built-in and user-defined exceptions.

Uploaded by

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

Python Week-6

The document discusses various object-oriented programming concepts in Python like inheritance, method overriding, and exception handling. It provides examples to illustrate: 1. Inheritance allows a child class to inherit attributes and behaviors from a parent class. There are different types of inheritance like single, multiple, multilevel and hierarchical. 2. Method overriding allows a child class to provide a specific implementation of a method defined in the parent class. The super() method can call the parent method. 3. Exception handling allows programs to deal with runtime errors gracefully using built-in and user-defined exceptions.

Uploaded by

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

RAGHU ENGINEERING COLLEGE (A)

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 to achieve single inheritance:


class BaseClassName:
statement block
class DerivedClassName (BaseClassName):
statement block
Program:
class One:
subject="Python"
def display(self):
print("From Base class")
class Two(One):
def show(self):
print("From Derived class")
print("Subject:",self.subject)
twoObj=Two()
twoObj.display()
twoObj.show()
Output:
From Base class
From Derived class
Subject: Python
super() method:
• super() method is used to refer the base class of the current working class.
• super() method can be used to gain access to inherited methods from a parent that has
been overwritten in current class.
• If we have members with same name in base class and derived class, then we can take
the help of the super() to access the base class member and self to access the its own
member.
The syntax to acces the base class members:
class BaseClassName:
memberName
class DerivedClassName (BaseClassName):
super().memberName
Program:
class One:
subject="Python"
def display(self):
print("From Base class")
class Two(One):
subject="Java"
def show(self):
print("From Derived class")
print("Subject in base class:",super().subject)
print("Subject in sub class:",self.subject)
twoObj=Two()
twoObj.display()
twoObj.show()
Output:
From Base class
From Derived class
Subject in base class: Python
Subject in sub class: Java
Multiple Inheritance
• When a single class is derived from more than one base class, it is called Multiple
Inheritance.
• The derived class has all the features of both the base classes 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.

The syntax for multi-level inheritance can be given as,


class BaseClassName:
statements
class FirstDerivedClass(BaseClassName):
statements
class SecondDerivedClass(FirstDerivedClassName):
statements
Program:
class Base:
def show1(self):
print("Base Class")
class FirstDerived(Base):
def show2(self):
print("First Derived Class")
class SecondDerived(FirstDerived):
def show3(self):
self.show1()
self.show2()
print("Second Derived Class")
sdObj=SecondDerived()
sdObj.show3()
Output:
Base Class
First Derived Class
Second Derived Class
The complexity arises as child inherits from parent and parent inherits from the
grandparent class. Python climbs an inheriting tree looking for attributes that is being
requested to be read from an object. It will check the in the instance, within class then parent
class and lastly from the grandparent class.

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.

The syntax for hierarchical inheritance can be given as,


class BaseClass:
statements
class DerivedClass1(BaseClass):
statements
class DerivedClass2(BaseClass):
statements
Program:
class Base:
def show1(self):
print("Base Class")
class FirstDerived(Base):
def show2(self):
print("First Derived Class")
class SecondDerived(Base):
def show3(self):
print("Second Derived Class")
fdObj=FirstDerived()
sdObj=SecondDerived()
fdObj.show1()
fdObj.show2()
sdObj.show1()
sdObj.show3()
Output:
Base Class
First Derived Class
Base Class
Second Derived Class
Method Overriding:
• Method Overriding is the ability of a class to change the implementation of a method
provided by one of its ancestors in the inheritance hierarchy.
• In Python method overriding occurs simply defining in the child class a method with
the same name of a method in the parent class.
• Once the method overridden, the method with same name from its base class can’t be
accessed with ‘self.methodName()’ statement. But it is possible by using
‘super().methodName()’ statement
• In Python, method overriding is one way of implementing polymorphism.
• It enables the programmers to assign a different meaning or usage to a variable,
function, or an object in different contexts.
Program:
class REI:
def show(self):
print("Raghu Educational Institutions")
class REC(REI):
def show(self):
print("Raghu Engineering College")
obj1=REC()
obj2=REI()
obj1.show()
obj2.show()
Output:
Raghu Engineering College
Raghu Educational Institutions
Program using super():
class REI:
def show(self):
print("Raghu Educational Institutions")
class REC(REI):
def show(self):
print("Raghu Engineering College")
def get(self):
super().show()
self.show()
obj1=REC()
obj1.get()
Output:
Raghu Educational Institutions
Raghu Engineering College
Example using super() in multiple inheritance:
Program:
class State:
state="Andhra Pradesh"
def show(self):
print("State:",self.state)
class City:
city="Vizag"
def show(self):
print("City:",self.city)
class College(City,State):
college="REC"
def show(self):
print("College:",self.college)
def get(self):
super().show()
self.show()
clgObj=College()
clgObj.get()
Output:
City: Vizag
College: REC
In this program, College class is derived from State and City classes. When we use
super().show() method, the show() inside City class will be invoked because City class is
consider as the super class as it is specified first in the multiple inheritance statement.
Exception:
An exception is an event that may cause abnormal termination of the program during
its execution.
Exceptions are categorized into two groups.
They are,

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:

Exception Cause of Error

AssertionError Raised when assert statement fails.

AttributeError Raised when attribute assignment or reference fails.

EOFError Raised when the input() functions hits end-of-file condition.

FloatingPointError Raised when a floating point operation fails.

ImportError Raised when the imported module is not found.

IndexError Raised when index of a sequence is out of range.

KeyError Raised when a key is not found in a dictionary.

KeyboardInterrupt Raised when the user hits interrupt key (Ctrl+c or delete).

MemoryError Raised when an operation runs out of memory.

NameError Raised when a variable is not found in local or global scope.

OverflowError Raised when result of an arithmetic operation is too large to be


represented.
RuntimeError Raised when an error does not fall under any other category.

SyntaxError Raised by parser when syntax error is encountered.

IndentationError Raised when there is incorrect indentation.

TypeError Raised when a function or operation is applied to an object of


incorrect type.
ValueError Raised when a function gets improper value.

ZeroDivisionError Raised when second operand of division or modulo operation is


zero.

Exception Handling:

 The process of handling the exception is called ‘Exception Handling’.


 When there is an exception, the user data may be corrupted.
 So, the exception should be handled by the programmer.
 In Python, there are some keywords like try, except, finally.
 These keywords are useful in the process of handling the exceptions.

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:

 The try statement in Python can have an optional finally block.


 This block is executed no matter what, and is generally used to release external
resources like file closing, database closing.

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:

 In python, we can specify an except block without mentioning any exception.


 When multiple except blocks are present, this type of except block if present should
be the last one that can serve as a wildcard.
 In this case, the exception type is taken as ‘Exception’ which is a super class of all the
type of built-in exceptions.
 This idea is to write a handler that would catch all types of exceptions.

Program:
try:
print(a)
except Exception:
print("Unknown defined exception..")

Output:
Unknown defined exception..

Raising Exceptions:

 Intentionally, we can raise an exception using the raise keyword.


 The general syntax for the raise statement is,
o raise Exception("Message")
 The above statement will create an Exception class object.
 args is the reference of the tuple of strings to be used for display a message to the
user.
 We can get the args values as below,

Program:
try:
raise Exception("Raised","Intentionally")
except Exception as exObj:
print(exObj.args)

Output:
('Raised', 'Intentionally')

User-defined Exceptions:

 A user can create his own exception using Exception class.


 Exception which is created by the user is called as ‘User-defined Exception’.
Steps to create user-defined exception:
1. User-defined exception class need to derived from the Exception class.
2. Override the constructor of Exception class to initialize a data member called ‘value’.

3. Override the __str__(self) method of Exception class to return a message when an


exception is raised.
4. Raise user-defined exception using ‘raise’ keyword whenever needed.

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

You might also like