Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Module 4

Download as pdf or txt
Download as pdf or txt
You are on page 1of 67

Course Code : CST283

Category : Minor
Offered by : Dept. of Computer Science and Engg.
Faculty in charge : Jaseela Beevi S

Python for Machine Learning


Dept. of CSE, TKMCE 1
Syllabus - Module IV

Design with classes - Objects and Classes, Methods, Instance Variables,


Constructor, Accessors and Mutators. Structuring classes with
Inheritance and Polymorphism. Abstract Classes. Exceptions - Handle a
single exception, handle multiple exceptions.

Dept. of CSE, TKMCE 2


Overview of OOP (Object Oriented Programming)
• Python is a multi-paradigm programming language. It supports different programming
approaches.

• One of the popular approaches to solve a programming problem is by creating objects.


This is known as Object-Oriented Programming (OOP).

An object has two characteristics:


(1) attributes
(2) behavior

Suppose a parrot is an object, as it has the following properties:

name, age, color as attributes


singing, dancing as behavior
Dept. of CSE, TKMCE 3
Object-oriented vs. Procedure-oriented Programming
Languages
Object-oriented Programming Procedural Programming
Object-oriented programming is the problem-solving Procedural programming uses a list of instructions to
approach and used where computation is done by do computation step by step.
using objects.
It makes the development and maintenance easier In procedural programming, It is not easy to
maintain the codes when the project becomes
lengthy.
It simulates the real world entity. So real-world It doesn't simulate the real world. It works on step
problems can be easily solved through oops. by step instructions divided into small parts called
functions.
It provides data hiding. So it is more secure than Procedural language doesn't provide any proper way
procedural languages. You cannot access private for data binding, so it is less secure.
data from anywhere.
Example of object-oriented programming languages Example of procedural languages are: C, Fortran,
is C++, Java, .Net, Python, C#, etc. Pascal, VB etc.
Dept. of CSE, TKMCE 4
Objects and Classes
• Object is an instance of a class.
• A class is a collection of data(variables) and methods(functions).
• A class is the basic structure of an object and is a set of attributes, which can be data
members or method members.

Some important terms in OOP are as follows:

üClass - They are defined by the user. The class provide basic structure for an object.
üData Member - A variable defined in either a class or an object. It holds the data
associated with the class or object.
üInstance variable - A variable that is defined in a method; its scope is only within the
object that defines it.
üClass Variable - A variable that is defined in the class and can be used by all the
instances of the class.

Dept. of CSE, TKMCE 5


üInstance - An object is an instance of the class.
üInstantiation - The process of creation of an object of a class.
üMethod - Methods are the functions that are defined in the definition of class and are
used by various instances of the class.
üFunction Overloading - A function defined more than one time with different behaviours
is known as function overloading. The operations performed by these functions are
different.
üInheritance - a class A that can use the characteristics of another class B is said to be a
derived class. ie., a class inherited from B. The process is called inheritance.

Data Encapsulation:
• In OOP, restrictions can be imposed on the access to methods and variables. Such
restrictions can be used to avoid accidental modification in the data and are known as
Encapsulation.
Dept. of CSE, TKMCE 6
• Polymorphism
The term polymorphism means that the object of a class can have many different forms
to respond in different ways to any message or action.

Dept. of CSE, TKMCE 7


Class Definition
• A class is a “blueprint” for creating objects.
• It can also be defined as a group of objects that share similar attributes and
relationships with each other.
eg., Fruit is a class and apple, mango and banana are its objects.
The attributes of these objects can be color, taste etc.

Syntax for defining a class


In python class is created by using a keyword class
After that, the first statement can be a docstring that contains the information about
the class.
In the body of class, the attributes (data members or method members) are defined.

Dept. of CSE, TKMCE 8


class <class name>(<parent class name>):
<method definition-1>

<method definition-n>

• In python, as soon as we define a class, the iterpreter instantly creates an object that
has the same name as the class name.
• We can create more objects of the same class. With the help of objects, we can access
the attributes defined in the class.

syntax for creating objects for a class


<object name> = <classname>

Dept. of CSE, TKMCE 9


Creating class Student
class Student:
'''Student details'''
def fill_details(self,name,branch,year):
self.name = name
self.branch = branch
self.year = year
print("A student detail object is created...")
def print_details(self):
print("Name: ",self.name)
print("Branch: ",self.branch)
print("Year: ",self.year)

Dept. of CSE, TKMCE 10


Creating an object of Student class
>>> s1 = Student()
>>> s2 = Student()
>>> s1.fill_details('Rahul','CSE','2020')
A student detail object is created...
>>> s1.print_details()
Name: Rahul
Branch: CSE
Year: 2020
>>> s2.fill_details('Akhil','ECE','2010')
A student detail object is created...
>>> s2.print_details()
Name: Akhil
Branch: ECE
Dept. of CSE, TKMCE 11
Year: 2010
Constructors in Python
A constructor is a special type of method (function) which is used to initialize the
instance members of the class.
Constructors can be of two types.

1. Parameterized Constructor
2. Non-parameterized Constructor

Creating the constructor in python


Class functions that begin with double underscore “__ “ are called special functions as
they have special meaning.
In Python, the method the __init__() simulates the constructor of the class. This
method is called when the class is instantiated. It accepts the self-keyword as a first
argument which allows accessing the attributes or method of the class.
Dept. of CSE, TKMCE 12
Example : Display a Complex Number
class ComplexNumber:
def __init__(self, r=0, i=0):
self.real = r
self.imag = i

def getNumber(self):
print(f'{self.real} + j{self.imag}')

num1 = ComplexNumber(2, 3)
num1.getNumber()

Output : 2+j3
Dept. of CSE, TKMCE 13
Example : Display Employee Details
class Employee:
def __init__(self, id, name): Output:
self.id = id
Id: 1
self.name = name
Name: john
Id: 2
def display(self):
Name: Anu
print("Id: %d\n Name: %s" % (self.id, self.name))

emp1 = Employee(1, "john")


emp2 = Employee(2, "Anu")

emp1.display()
emp2.display()
Dept. of CSE, TKMCE 14
Python Non-Parameterized Constructor Python Parameterized Constructor

The non-parameterized constructor uses when The parameterized constructor has multiple
we do not want to manipulate the value or the parameters along with the self.
constructor that has only self as an argument.
class Student:
class Student: def __init__(self, name):
def __init__(self): print("This is parameterized constructor")
print("This is non parameterized self.name = name
constructor")
def show(self):
def show(self, name): print("Hello ", self.name)
print("Hello ", name)

s1 = Student() s1 = Student("Rahul")
s1.show("Roshan") s1.show()

output: output:
This is non parameterized constructor This is parameterized constructor
Hello Roshan Hello Rahul
Dept. of CSE, TKMCE 15
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.

class Student:
name = "Jeevan"
rollno = 101

def show(self):
print("Name: ", self.name)
print("Roll No: ", self.rollno)
s1 = Student()
s1.show()

Output:
Name: Jeevan
Roll No: 101 Dept. of CSE, TKMCE 16
Example : The Student class
A course-management application needs to represent information about students in a
course. Each student has a name and a list of test scores. We can use these as the
attributes of a class named Student. The Student class should allow the user to view a
student’s name, view a test score at a given position (counting from 1), reset a test
score at a given position, view the highest test score, view the average test score, and
obtain a string representation of the student’s information.

The __str__ Method :


Many built-in Python classes usually include an __str__ method. This method builds
and returns a string representation of an object’s state. When the str function is called
with an object, that object’s __str__ method is automatically invoked to obtain the
string that str returns.

Dept. of CSE, TKMCE 17


"""
File: student.py
Resources to manage a student's name and test scores.
"""
class Student(object):
"""Represents a student."""
def __init__(self, name, number):
"""Constructor creates a Student with the given
name and number of scores and sets all scores
to 0."""
self.name = name
self.scores = []
for count in range(number):
self.scores.append(0)

Dept. of CSE, TKMCE 18


def getName(self):
"""Returns the student's name."""
return self.name
def setScore(self, i, score):
"""Resets the ith score, counting from 1."""
self.scores[i - 1] = score
def getScore(self, i):
"""Returns the ith score, counting from 1."""
return self.scores[i - 1]
def getAverage(self):
"""Returns the average score."""
return sum(self.scores) / len(self.scores)

Dept. of CSE, TKMCE 19


def getHighScore(self):
"""Returns the highest score."""
return max(self.scores)
def __str__(self):
"""Returns the string representation of the
student."""
return "Name: " + self.name + "\nScores: " + \
" ".join(map(str, self.scores))

Dept. of CSE, TKMCE 20


Accessors and Mutators
• The Methods that allow a user to observe but not change the state of an object are
called accessors.
• Methods that allow a user to modify an object’s state are called mutators.

Accessor Method: This method is used to access the state of the object i.e, the data
hidden in the object can be accessed from this method. However, this method cannot
change the state of the object, it can only access the data hidden. We can name these
methods with the word get.

Mutator Method: This method is used to mutate/modify the state of an object i.e, it
alters the hidden value of the data variable. It can set the value of a variable instantly
to a new value. This method is also called as update method. Moreover, we can name
these methods with the word set.
Dept. of CSE, TKMCE 21
Example : Accessors and Mutators
class Fruit:
def __init__(self, name):
self.name = name Output:
First fruit name: Apple
Second fruit name: Grape
def setFruitName(self, name):
self.name = name

def getFruitName(self):
return self.name

f1 = Fruit("Apple")
print("First fruit name: ", f1.getFruitName())
f1.setFruitName("Grape")
print("Second fruit name: ", f1.getFruitName())
Dept. of CSE, TKMCE 22
Inheritance in Python
• Inheritance is an important aspect of the object-oriented paradigm. Inheritance
provides code reusability to the program because we can use an existing class to
create a new class instead of creating it from scratch.
• In inheritance, the child class acquires the properties and can access all the data
members and functions defined in the parent class. A child class can also provide its
specific implementation to the functions of the parent class.

Syntax:
class derived class name(base class):
<class-suite>

Dept. of CSE, TKMCE 23


Types of Inheritance

Dept. of CSE, TKMCE 24


Single Inheritance
• When a child class inherits from only one parent class, it is called single inheritance.
• class derive-class(<base class >):
<class - suite>
Person

class Person: class Employee(Person):


def __init__(self, name): def isEmployee(self):
self.name = name return True
Employee
def getName(self):
return self.name p = Person("Anu")
print(p.getName(),
def isEmployee(self): p.isEmployee())
return False
e = Employee("Ammu") Output:
print(e.getName(), Anu False
e.isEmployee()) Ammu True

Dept. of CSE, TKMCE 25


Multiple inheritance
• When a child class inherits from multiple parent classes, it is called multiple
inheritance.
• class derive-class(<base class 1>, <base class 2>, ..... <base class n>):
<class - suite>

Person Student

Resident

Dept. of CSE, TKMCE 26


class Person: class Student:
def __init__(self, name, age): def __init__(self, rollno):
self.name = name self.rollno = rollno
self.age = age def getRollno(self):
print(self.rollno)
def showName(self):
print(self.name) class Resident(Person, Student):
def __init__(self, name, age, rollno):
Person.__init__(self, name, age)
def showAge(self): Student.__init__(self, rollno)
print(self.age)

Dept. of CSE, TKMCE 27


r = Resident("Roshan", 21, 101)
r.showName()
r.showAge()
r.getRollno()

Output:
Roshan
21
101

Dept. of CSE, TKMCE 28


Resolving the Conflict with Python Multiple Inheritance :
class A: class C(A, B):
def __init__(self): def __init__(self):
self.name = "John" A.__init__(self)
self.age = 23 B.__init__(self)

def getName(self): def getName(self):


return self.name return self.name

C1 = C()
class B: print(C1.getName())
def __init__(self):
self.name = "Richard"
self.id = 32 Output:
Richard
def getName(self):
return self.name Dept. of CSE, TKMCE 29
Method Resolution Order (MRO)

MRO works in a depth first left to right way. super() in the __init__ method indicates
the class that is in the next hierarchy. At first the the super() of C indicates A.

Then super in the constructor of A searches for its superclass. If it doesn’t find any, it
executes the rest of the code and returns. So the order in which constructors are called
here is:

C -> A -> B

Dept. of CSE, TKMCE 30


Resolving the Conflict with Python Multiple Inheritance :
def getName(self):
class A: return self.name
def __init__(self):
super().__init__() class C(A, B):
self.name = 'John' def __init__(self):
self.age = 23 super().__init__()

def getName(self): def getName(self):


return self.name return self.name

class B: C1 = C()
def __init__(self): print(C1.getName())
super().__init__() print(C.__mro__)
self.name = 'Richard'
self.id = '32' Output : John
Dept. of CSE, TKMCE 31
Multilevel Inheritance
• This is achieved when a derived class inherits another derived class. There is no limit
on the number of levels up to which, the multi-level inheritance is achieved in python.

• Syntax
First
class class1:
<class-suite>
class class2(class1):
Second
<class suite>
class class3(class2):
<class suite> Third

Dept. of CSE, TKMCE 32


class First: t = Third()
def first(self): t.first()
print("I am the first class") t.second()
t.third()

class Second(First):
def second(self): Output:
print("I am the second class") I am the first class
I am the second class
I am the third class
class Third(Second):
def third(self):
print("I am the third class")

Dept. of CSE, TKMCE 33


Hierarchical Inheritance
• When more than one derived classes are created from a single base – it is called
hierarchical inheritance.
• Syntax
class class1:
Parent
<class-suite>
class class2(class1):
<class suite>
class class3(class1):
<class suite>
Child-1 Child-2

Dept. of CSE, TKMCE 34


class Parent:
def func1(self): c1 = Child1()
print("This function is in c2 = Child2()
Parent")
c1.func1()
c1.func2()
class Child1(Parent):
def func2(self): c2.func1()
print("This function is in c2.func3()
child1")

Output:
class Child2(Parent):
def func3(self): This function is in child1
print("This function is in This function is in Parent
child3") This function is in child3
Dept. of CSE, TKMCE 35
Hybrid Inheritance
• The hybrid inheritance is the combination of more than one type of inheritance. We
may use any combination as a single with multiple inheritances, multi-level with
multiple inheritances, etc.

B C

Dept. of CSE, TKMCE


D 36
Use the super() Function
• Python also has a super() function that will make the child class inherit all the
methods and properties from its parent:
• By using the super() function, you do not have to use the name of the parent element,
it will automatically inherit the methods and properties from its parent.

class Person: x = Student("John", "Samuel")


def __init__(self, fname, lname): x.printname()
self.firstname = fname
self.lastname = lname Output:
John Samuel
def printname(self):
print(self.firstname, self.lastname)

class Student(Person):
def __init__(self, fname, lname):
super().__init__(fname, lname) Dept. of CSE, TKMCE 37
Polymorphism in Python
• The word polymorphism means having many forms. In programming, polymorphism
means same function name (but different signatures) being uses for different types.

• It is a very important concept in programming. It refers to the use of a single type


entity (method, operator or object) to represent different types in different scenarios.

• Polymorphism in addition operator

num1 = 1 str1 = "Python"


num2 = 2 str2 = "Programming"
print(num1+num2) print(str1+" "+str2)
o/p : 3 o/p : Python Programming

Dept. of CSE, TKMCE 38


• Function polymorphism in python

print(len("Programiz"))
print(len(["Python", "Java", "C"]))
print(len({"Name": "John", "Address": "Nepal"}))

Dept. of CSE, TKMCE 39


• Polymorphism in Class Methods

class Rectangle: class Shape:


def __init__(self, length, width): def __init__(self, length, width):
self.length = length self.length = length
self.width = width self.width = width

def findArea(self): def findArea(self):


print("Area: ", self.length * self.width) print("Area: ", self.length * self.width)

def printInfo(self): def printInfo(self):


print("This is a Rectangle") print("This is a geometric shape")

Dept. of CSE, TKMCE 40


rect1 = Rectangle(12, 10)
sh1 = Shape(10, 13)

for value in (rect1, sh1):


value.printInfo()
value.findArea()

Output:

This is a Rectangle
Area: 120
This is a geometric shape
Area: 130

Dept. of CSE, TKMCE 41


• Polymorphism and Inheritance

Like in other programming languages, the child classes in Python also inherit methods
and attributes from the parent class. We can redefine certain methods and attributes
specifically to fit the child class, which is known as Method Overriding.

In Python, to override a method, you have to meet certain conditions, and they are:

• You can’t override a method within the same class. It means you have to do it in
the child class using the Inheritance concept.

• To override the Parent Class method, you have to create a method in the Child
class with the same name and the same number of parameters.

Dept. of CSE, TKMCE 42


class Parent:
def __init__(self):
self.value = "Inside Parent" obj1 = Parent()
obj2 = Child()
def show(self):
print(self.value) obj1.show()
obj2.show()

class Child(Parent):
def __init__(self): Output:
self.value = "Inside Child"
Inside Parent
def show(self): Inside Child
print(self.value)

Dept. of CSE, TKMCE 43


Abstraction
Abstraction means hiding the complexity and only showing the essential features of the
object. So in a way, Abstraction means hiding the real implementation and we, as a user,
knowing only how to use it.

Abstract Class in Python


• An abstract class is a class that contains one or more abstract methods.
• An Abstract method is a method that generally doesn’t have any implementation,
it is left to the sub classes to provide implementation for the abstract methods.
• Abstract class can’t be instantiated so it is not possible to create objects of
an abstract class.

Dept. of CSE, TKMCE 44


Abstract Class in Python
In Python abstract class is created by deriving from the meta class ABC which belongs to
the abc (Abstract Base Class) module.

Syntax for creating Abstract Class


from abc import ABC
class MyClass(ABC):

Abstract Method in Python

• For defining abstract methods in an abstract class, method has to be decorated with
@abstractmethod decorator.
• From abc module @abstractmethod decorator has to be imported to use that
annotation.

Dept. of CSE, TKMCE 45


Syntax for defining abstract method in abstract class in Python

from abc import ABC, abstractmethod


class MyClass(ABC):
@abstractmethod
def mymethod(self):
pass #empty body

Dept. of CSE, TKMCE 46


Important points about abstract class in Python

• Abstract class can have both concrete methods as well as abstract methods.

• Abstract class works as a template for other classes.

• Abstract class can’t be instantiated so it is not possible to create objects of


an abstract class.

• Generally abstract methods defined in abstract class don’t have any body but it
is possible to have abstract methods with implementation in abstract class.

• If any abstract method is not implemented by the derived class Python throws
an error.

Dept. of CSE, TKMCE 47


class Child2(Parent):
from abc import ABC, abstractmethod def vary(self):
print("I am vary method of child2")
class Parent(ABC):
def common(self): obj1 = Child1()
print("I am the common of parent") obj1.common()
obj1.vary()
@abstractmethod obj2 = Child2()
def vary(self): obj2.common()
pass obj2.vary()

class Child1(Parent): o/p


def vary(self): I am the common of parent
print("I am vary of child1") I am vary of child1
I am the common of parent
I am vary method of child2
Dept. of CSE, TKMCE 48
Errors and Exceptions

• Two common kinds of errors that you may have to deal with are
üSyntax errors
üExceptions

Syntax Errors:
It occur when you type the code incorrectly.
Exceptions:
They are different from syntax errors. They occur during the execution of a program
when something unexpected happens.

Dept. of CSE, TKMCE 49


Some Common Built-in Exceptions
• NameError: This exception is raised when the program cannot find a local or
global name. The name that could not be found is included in the error message.

• TypeError: This exception is raised when a function is passed an object of the


inappropriate type as its argument. More details about the wrong type are
provided in the error message.

• ValueError: This exception occurs when a function argument has the right type
but an inappropriate value.

Dept. of CSE, TKMCE 50


• NotImplementedError: This exception is raised when an object is supposed to support
an operation but it has not been implemented yet. You should not use this error when
the given function is not meant to support the type of input argument. In those
situations, raising a TypeError exception is more appropriate.

• ZeroDivisionError: This exception is raised when you provide the second argument for
a division or modulo operation as zero.

• FileNotFoundError: This exception is raised when the file or directory that the program
requested does not exist

Dept. of CSE, TKMCE 51


Handling an Exception
a = True
while a:
x = int(input("Enter a number: "))
print("Dividing 50 by", x, "will give you:", 50/x)

You will get Value Error on entering decimal number or string as input.

To handle the exception,


The first step of the process is to include the code that you think might raise an
exception inside the try clause. The next step is to use the except keyword to
handle the exception that occurred in the above code

Dept. of CSE, TKMCE 52


a = True
while a:
try:
x = int(input("Please enter a number: "))
print("Dividing 50 by", x, "will give you: ", 50/x)

except ValueError:
print("The input was not an integer. Please try again...")

Output:
Please enter a number: a
The input was not an integer. Please try again...
Please enter a number: 2
Dividing 50 by 2 will give you: 25.0
Dept. of CSE, TKMCE 53
• If no exception was raised, the program skips the except clause and the rest of the
code executes normally.
• If an exception is raised, the program skips the remaining code inside the try clause
and the type of the exception is matched with the name of the exception after the
except keyword.
In case of a match, the code inside the except clause is executed
first, and then the rest of the code after the try clause is executed normally.
• When you enter an integer as an input, the program gives you the final result of the
division.
• When a non-integral value is provided, the program prints a message asking you to try
and enter an integer again.
• Note that this time, the program does not abruptly quit when you provide some
invalid input

Dept. of CSE, TKMCE 54


• You can also handle multiple exceptions using a single except clause by passing these
exceptions to the clause as a tuple.

except (ZeroDivisionError, ValueError, TypeError):


print("Something has gone wrong..")

• One possible use of catching all exceptions is to properly print out the exception error on
screen like the following code:

import math
import sys
try:
result = math.factorial(2.4)
except:
print("Something Unexpected has happened.",sys.exc_info()[0])
else:
print("The factorial is", result)
Dept. of CSE, TKMCE 55
Using the Else Clause
• The else clause is meant to contain code that needs to be executed if the try clause did
not raise any exceptions.
• if you decide to use an else clause, you should include it after all the except clauses but
before the finally block.

a = True
while a:
try:
x = int(input("Please enter a number: "))
except ValueError:
print("The input was not a valid integer. Please try again...")
else:
print("Dividing 50 by", x, "will give you :", 50 / x)

Dept. of CSE, TKMCE 56


Using the Finally Clause
• The code inside the finally clause is always executed irrespective of whether the try block
raised an exception.

a = True
while a:
try:
x = int(input("Please enter a number: "))
except ValueError:
print("The input was not a valid integer. Please try again...")
else:
print("Dividing 50 by", x,"will give you :", 50/x)
finally:
print("Already did everything necessary.")
Dept. of CSE, TKMCE 57
Output:

Please enter a number: 2


Dividing 50 by 2 will give you : 25.0
Already did everything necessary.
Please enter a number: d
The input was not a valid integer. Please try again...
Already did everything necessary.
Please enter a number:

Dept. of CSE, TKMCE 58


Exception with Arguments
Using arguments for Exceptions in Python is useful for the following reasons:
üIt can be used to gain additional information about the error encountered.
üAs contents of an Argument can vary depending upon different types of Exceptions
in Python, Variables can be supplied to the Exceptions to capture the essence of the
encountered errors. Same error can occur of different causes, Arguments helps us
identify the specific cause for an error using the except clause.
üIt can also be used to trap multiple exceptions, by using a variable to follow the tuple
of Exceptions.

Dept. of CSE, TKMCE 59


Arguments in Built-in Exceptions
try:
s = "Hello Python"
b = float(100+50/0) try:
except Exception as argument: b = float(s/20)
print("This is the argument\n", argument) except Exception as argument:
print("This is the argument: \n",
argument)
Output:
This is the argument Output:
division by zero
This is the argument:
unsupported operand type(s) for /:
'str' and 'int'
Dept. of CSE, TKMCE 60
Raising exceptions
An exception can be raised forcefully by using the raise clause in Python. It is useful in
that scenario where we need to raise an exception to stop the execution of the program.
Syntax: raise Exception_class,<value>

• To raise an exception, the raise statement is used. The exception class name follows it.
• An exception can be provided with a value that can be given in the parenthesis.
• To access the value "as" keyword is used. "e" is used as a reference variable
which stores the value of the exception.
• We can pass the value to an exception to specify the exception type.

Dept. of CSE, TKMCE 61


try:
age = int(input("Enter the age:"))
if(age<18):
raise ValueError
else:
print("the age is valid")
except ValueError:
print("The age is not valid")

Output:

Enter the age:16


The age is not valid

Dept. of CSE, TKMCE 62


User-Defined Exceptions
In Python, users can define custom exceptions by creating a new class. This exception
class has to be derived, either directly or indirectly, from the built-in Exception class.
Most of the built-in exceptions are also derived from this class.

class customError(Exception):
pass
raise customError

Here, we have created a user-defined exception called CustomError which inherits


from the Exception class. This new exception, like other exceptions, can be raised using
the raise statement with an optional error message.

Dept. of CSE, TKMCE 63


Deriving Error from Super class
üSuper class exceptions are created when a module needs to handle several distinct
errors.
üOne of the common way of doing this is to create a base class for exceptions defined
by that module.
üFurther, various sub classes are defined to create specific exception classes for
different error conditions.

Dept. of CSE, TKMCE 64


class Error(Exception): except ValueTooSmallError:
pass print("This value is too small, try
class ValueTooSmallError(Error): again!")
pass
class ValueTooLargeError(Error): except ValueTooLargeError:
pass print("This value is too large, try
number = 10 again!")
while True:
try: print("Congratulations! You guessed it
i_num = int(input("Enter a number: ")) correctly.")
if i_num < number:
raise ValueTooSmallError
elif i_num > number:
raise ValueTooLargeError
break

Dept. of CSE, TKMCE 65


Output:
Enter a number: 3
This value is too small, try again!
Enter a number: 5
This value is too small, try again!
Enter a number: 11
This value is too large, try again!
Enter a number: 10
Congratulations! You guessed it correctly.

Dept. of CSE, TKMCE 66


Thank You
Dept. of CSE, TKMCE 67

You might also like