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

Unit 5 Python Programming

1. The document discusses exception handling in Python. It defines what exceptions are and explains that they interrupt normal program flow. It then covers built-in exceptions, handling exceptions using try-except blocks, and raising custom exceptions. 2. Key aspects of exception handling covered include using try-except blocks to catch exceptions, optionally using an else block, handling multiple exceptions, and ensuring code in finally blocks always executes. Custom exceptions can be raised using raise. 3. Exception handling allows programs to continue running despite errors, improve robustness, and ensure resources are always cleaned up. The try-except statement is Python's main mechanism for exception handling.

Uploaded by

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

Unit 5 Python Programming

1. The document discusses exception handling in Python. It defines what exceptions are and explains that they interrupt normal program flow. It then covers built-in exceptions, handling exceptions using try-except blocks, and raising custom exceptions. 2. Key aspects of exception handling covered include using try-except blocks to catch exceptions, optionally using an else block, handling multiple exceptions, and ensuring code in finally blocks always executes. Custom exceptions can be raised using raise. 3. Exception handling allows programs to continue running despite errors, improve robustness, and ensure resources are always cleaned up. The try-except statement is Python's main mechanism for exception handling.

Uploaded by

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

BCA Semester 6th

BCA614 Python Programming


Unit V Exception Handling and OOPs Concepts

Python Exception
An exception can be defined as an unusual condition in a program resulting in the interruption
in the flow of the program.

Whenever an exception occurs, the program stops the execution, and thus the further code is
not executed. Therefore, an exception is the run-time errors that are unable to handle to Python
script. An exception is a Python object that represents an error

Python provides a way to handle the exception so that the code can be executed without any
interruption. If we do not handle the exception, the interpreter doesn't execute all the code that
exists after the exception.

Python has many built-in exceptions that enable our program to run without interruption and
give the output. These exceptions are given below:

Common Exceptions
Python provides the number of built-in exceptions, but here we are describing the common
standard exceptions. A list of common exceptions that can be thrown from a standard Python
program is given below.

1. ZeroDivisionError: Occurs when a number is divided by zero.


2. NameError: It occurs when a name is not found. It may be local or global.
3. IndentationError: If incorrect indentation is given.
4. IOError: It occurs when Input Output operation fails.
5. EOFError: It occurs when the end of the file is reached, and yet operations are being
performed.

The problem without handling exceptions


As we have already discussed, the exception is an abnormal condition that halts the execution
of the program.

Suppose we have two variables a and b, which take the input from the user and perform the
division of these values. What if the user entered the zero as the denominator? It will interrupt
the program execution and through a ZeroDivision exception. Let's see the following example.

Example
1. a = int(input("Enter a:"))
2. b = int(input("Enter b:"))

1
3. c = a/b
4. print("a/b = %d" %c)
5. #other code:
6. print("Hi I am other part of the program")
Output:

Enter a:10
Enter b:0
Traceback (most recent call last):
File "exception-test.py", line 3, in <module>
c = a/b;
ZeroDivisionError: division by zero

The above program is syntactically correct, but it through the error because of unusual input.
That kind of programming may not be suitable or recommended for the projects because these
projects are required uninterrupted execution. That's why an exception-handling plays an
essential role in handling these unexpected exceptions. We can handle these exceptions in the
following way.

Exception handling in python


The try-except statement

If the Python program contains suspicious code that may throw the exception, we must place
that code in the try block. The try block must be followed with the except statement, which
contains a block of code that will be executed if there is some exception in the try block.

Syntax

1. try:
2. #block of code
3. except Exception1:
4. #block of code
5. except Exception2:
6. #block of code

2
7. #other code

Consider the following example.

Example 1

1. try:
2. a = int(input("Enter a:"))
3. b = int(input("Enter b:"))
4. c = a/b
5. except:
6. print("Can't divide with zero")

Output:

Enter a:10
Enter b:0
Can't divide with zero

We can also use the else statement with the try-except statement in which, we can place the
code which will be executed in the scenario if no exception occurs in the try block.

The syntax to use the else statement with the try-except statement is given below.

1. try:
2. #block of code
3. except Exception1:
4. #block of code
5. else:
6. #this code executes if no except block is executed

3
Consider the following program.

Example 2

1. try:
2. a = int(input("Enter a:"))
3. b = int(input("Enter b:"))
4. c = a/b
5. print("a/b = %d"%c)
6. # Using Exception with except statement. If we print(Exception) it will return exceptio
n class
7. except Exception:
8. print("can't divide by zero")
9. print(Exception)
10. else:
11. print("Hi I am else block")

Output:

Enter a:10
Enter b:0
can't divide by zero
<class 'Exception'>

4
The except statement with no exception
Python provides the flexibility not to specify the name of exception with the exception
statement.

Consider the following example.

Example

1. try:
2. a = int(input("Enter a:"))
3. b = int(input("Enter b:"))
4. c = a/b;
5. print("a/b = %d"%c)
6. except:
7. print("can't divide by zero")
8. else:
9. print("Hi I am else block")

The except statement using with exception variable


We can use the exception variable with the except statement. It is used by using
the as keyword. This object will return the cause of the exception. Consider the following
example:

try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b
print("a/b = %d"%c)
# Using exception object with the except statement
except Exception as e:
print("can't divide by zero")
print(e)
else:
print("Hi I am else block")

Output:

Enter a:10
Enter b:0

5
can't divide by zero
division by zero

Points to remember
1. Python facilitates us to not specify the exception with the except statement.
2. We can declare multiple exceptions in the except statement since the try block may
contain the statements which throw the different type of exceptions.
3. We can also specify an else block along with the try-except statement, which will be
executed if no exception is raised in the try block.
4. The statements that don't throw the exception should be placed inside the else block.

Example

1. try:
2. #this will throw an exception if the file doesn't exist.
3. fileptr = open("file.txt","r")
4. except IOError:
5. print("File not found")
6. else:
7. print("The file opened successfully")
8. fileptr.close()

Output:
File not found

Declaring Multiple Exceptions


The Python allows us to declare the multiple exceptions with the except clause. Declaring
multiple exceptions is useful in the cases where a try block throws multiple exceptions. The
syntax is given below.

Syntax

1. try:
2. #block of code
3. except (<Exception 1>,<Exception 2>,<Exception 3>,...<Exception n>)
4. #block of code
5. else:
6. #block of code

Consider the following example.

6
try:
a=10/0;
except(ArithmeticError, IOError):
print("Arithmetic Exception")
else:
print("Successfully Done")

Output:
Arithmetic Exception

The try...finally block


Python provides the optional finally statement, which is used with the try statement. It is
executed no matter what exception occurs and used to release the external resource. The finally
block provides a guarantee of the execution.

We can use the finally block with the try block in which we can pace the necessary code, which
must be executed before the try statement throws an exception.

The syntax to use the finally block is given below.

Syntax

1. try:
2. # block of code
3. # this may throw an exception
4. finally:
5. # block of code
6. # this will always be executed

7
1. try:
2. fileptr = open("file2.txt","r")
3. try:
4. fileptr.write("Hi I am good")
5. finally:
6. fileptr.close()
7. print("file closed")
8. except:
9. print("Error")

Output:

file closed
Error

8
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.

For example, there is a program that requires 2GB memory for execution, and if the program
tries to occupy 2GB of memory, then we can raise an exception to stop the execution of the
program.

The syntax to use the raise statement is given below.

Syntax

1. raise Exception_class,<value>

Points to remember

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

Example

1. try:
2. age = int(input("Enter the age:"))
3. if(age<18):
4. raise ValueError
5. else:
6. print("the age is valid")
7. except ValueError:
8. print("The age is not valid")
Output:

Enter the age:17


The age is not valid

Example 2 Raise the exception with message


1. try:
2. num = int(input("Enter a positive integer: "))
3. if(num <= 0):
4. # we can pass the message in the raise statement

9
5. raise ValueError("That is a negative number!")
6. except ValueError as e:
7. print(e)

Output:
Enter a positive integer: -5
That is a negative number!
Example 3
1. try:
2. a = int(input("Enter a:"))
3. b = int(input("Enter b:"))
4. if b == 0:
5. raise ArithmeticError
6. else:
7. print("a/b = ",a/b)
8. except ArithmeticError:
9. print("The value of b can't be 0")
Output:
Enter a:10
Enter b:0
The value of b can't be 0

Custom Exception
The Python allows us to create our exceptions that can be raised from the program and caught
using the except clause. However, we suggest you read this section after visiting the Python
object and classes.

Consider the following example.

Example

1. class ErrorInCode(Exception):
2. def __init__(self, data):
3. self.data = data
4. def __str__(self):
5. return repr(self.data)

1. try:
2. raise ErrorInCode(2000)
3. except ErrorInCode as ae:
4. print("Received error:", ae.data)

10
Output:
Received error: 2000
Python OOPs Concepts
Like other general-purpose programming languages, Python is also an object-oriented
language since its beginning. It allows us to develop applications using an Object-Oriented
approach. In Python, we can easily create and use classes and objects.

An object-oriented paradigm is to design the program using classes and objects. The object is
related to real-word entities such as book, house, pencil, etc. The oops concept focuses on
writing the reusable code. It is a widespread technique to solve the problem by creating objects.

Major principles of object-oriented programming system are given below.

o Class
o Object
o Method
o Inheritance
o Polymorphism
o Data Abstraction
o Encapsulation

Class
The class can be defined as a collection of objects. It is a logical entity that has some specific
attributes and methods. For example: if you have an employee class, then it should contain an
attribute and method, i.e. an email id, name, age, salary, etc.

Syntax
1. class ClassName:
2. <statement-1>
3. .
4. .
5. <statement-N>
Object
The object is an entity that has state and behavior. It may be any real-world object like the
mouse, keyboard, chair, table, pen, etc.

Everything in Python is an object, and almost everything has attributes and methods. All
functions have a built-in attribute __doc__, which returns the doc string defined in the function
source code.

11
When we define a class, it needs to create an object to allocate the memory. Consider the
following example.

Example:

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 model
name and year. We have created a c1 object to access the class attribute. The c1 object will
allocate memory for these values.

Method
The method is a function that is associated with an object. In Python, a method is not unique
to class instances. Any object type can have methods.

Inheritance
Inheritance is the most important aspect of object-oriented programming, which simulates the
real-world concept of inheritance. It specifies that the child object acquires all the properties
and behaviors of the parent object.

By using inheritance, we can create a class which uses all the properties and behavior of another
class. The new class is known as a derived class or child class, and the one whose properties
are acquired is known as a base class or parent class.

It provides the re-usability of the code.

Polymorphism
Polymorphism contains two words "poly" and "morphs". Poly means many, and morph means
shape. By polymorphism, we understand that one task can be performed in different ways. For
example - you have a class animal, and all animals speak. But they speak differently. Here, the
"speak" behaviour is polymorphic in a sense and depends on the animal. So, the abstract
"animal" concept does not actually "speak", but specific animals (like dogs and cats) have a
concrete implementation of the action "speak".

12
Encapsulation
Encapsulation is also an essential aspect of object-oriented programming. It is used to restrict
access to methods and variables. In encapsulation, code and data are wrapped together within
a single unit from being modified by accident.

Data Abstraction
Abstraction is used to hide internal details and show only functionalities. Abstracting
something means to give names to things so that the name captures the core of what a function
or a whole program does.

Object-oriented vs. Procedure-oriented Programming languages


The difference between object-oriented and procedure-oriented programming is given below:

Index Object-oriented Programming Procedural Programming

1. Object-oriented programming is the Procedural programming uses a list of


problem-solving approach and used where instructions to do computation step by
computation is done by using objects. step.

2. It makes the development and maintenance In procedural programming, It is not easy


easier. to maintain the codes when the project
becomes lengthy.

3. It simulates the real world entity. So real- It doesn't simulate the real world. It works
world problems can be easily solved on step by step instructions divided into
through oops. small parts called functions.

4. It provides data hiding. So it is more secure Procedural language doesn't provide any
than procedural languages. You cannot proper way for data binding, so it is less
access private data from anywhere. secure.

5. Example of object-oriented programming Example of procedural languages are: C,


languages is C++, Java, .Net, Python, C#, Fortran, Pascal, VB etc.
etc.

Python Class and Objects


A class is a virtual entity and can be seen as a blueprint of an object. The class came into
existence when it instantiated. Let's understand it by an example.

13
Suppose a class is a prototype of a building. A building contains all the details about the floor,
rooms, doors, windows, etc. we can make as many buildings as we want, based on these details.
Hence, the building can be seen as a class, and we can create as many objects of this class.

On the other hand, the object is the instance of a class. The process of creating an object can
be called instantiation.

In this section of the tutorial, we will discuss creating classes and objects in Python. We will
also discuss how a class attribute is accessed by using the object.

Creating classes in Python

In Python, a class can be created by using the keyword class, followed by the class name. The
syntax to create a class is given below.

Syntax

1. class ClassName:
2. #statement_suite

In Python, we must notice that each class is associated with a documentation string which can
be accessed by using <class-name>.__doc__. A class contains a statement suite including
fields, constructor, function, etc. definition.

Consider the following example to create a class Employee which contains two fields as
Employee id, and name.

The class also contains a function display(), which is used to display the information of
the Employee.

Example

1. class Employee:
2. id = 10
3. name = "Devansh"
4. def display (self):
5. print(self.id,self.name)

Here, the self is used as a reference variable, which refers to the current class object. It is always
the first argument in the function definition. However, using self is optional in the function
call.

14
The self-parameter
The self-parameter refers to the current instance of the class and accesses the class variables.
We can use anything instead of self, but it must be the first parameter of any function which
belongs to the class.

Creating an instance of the class


A class needs to be instantiated if we want to use the class attributes in another class or method.
A class can be instantiated by calling the class using the class name.

The syntax to create the instance of the class is given below.

1. <object-name> = <class-name>(<arguments>)

The following example creates the instance of the class Employee defined in the above
example.

Example

1. class Employee:
2. id = 10
3. name = "John"
4. def display (self):
5. print("ID: %d \nName: %s"%(self.id, self.name))
6. # Creating a emp instance of Employee class
7. emp = Employee()
8. emp.display()

Output:

ID: 10
Name: John

In the above code, we have created the Employee class which has two attributes named id and
name and assigned value to them. We can observe we have passed the self as parameter in
display function. It is used to refer to the same class attribute.

We have created a new instance object named emp. By using it, we can access the attributes
of the class.

15
Delete the Object
We can delete the properties of the object or object itself by using the del keyword. Consider
the following example.

Example
1. class Employee:
2. id = 10
3. name = "John"
4. def display(self):
5. print("ID: %d \nName: %s" % (self.id, self.name))
6. # Creating a emp instance of Employee class
7. emp = Employee()
8. # Deleting the property of object
9. del Employee.id
10. # Deleting the object itself
11. del emp
12. emp.display()

It will through the Attribute error because we have deleted the object emp.

Python Constructor
A constructor is a special type of method (function) which is used to initialize the instance
members of the class.

In C++ or Java, the constructor has the same name as its class, but it treats constructor
differently in Python. It is used to create an object.

Constructors can be of two types.

1. Parameterized Constructor
2. Non-parameterized Constructor

Constructor definition is executed when we create the object of this class. Constructors also
verify that there are enough resources for the object to perform any start-up task.

Creating the constructor in python


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.

16
We can pass any number of arguments at the time of creating the class object, depending upon
the __init__() definition. It is mostly used to initialize the class attributes. Every class must
have a constructor, even if it simply relies on the default constructor.

Consider the following example to initialize the Employee class attributes.

Example
1. class Employee:
2. def __init__(self, name, id):
3. self.id = id
4. self.name = name
5. def display(self):
6. print("ID: %d \nName: %s" % (self.id, self.name))
7. emp1 = Employee("John", 101)
8. emp2 = Employee("David", 102)
9. # accessing display() method to print employee 1 information
10. emp1.display()
11. # accessing display() method to print employee 2 information
12. emp2.display()

Output:
ID: 101
Name: John
ID: 102
Name: David

Counting the number of objects of a class


The constructor is called automatically when we create the object of the class. Consider the
following example.

Example
1. class Student:
2. count = 0
3. def __init__(self):
4. Student.count = Student.count + 1
5. s1=Student()
6. s2=Student()
7. s3=Student()
8. print("The number of students:",Student.count)
Output:
The number of students: 3

17
Python Non-Parameterized Constructor

The non-parameterized constructor uses when we do not want to manipulate the value
or the constructor that has only self as an argument. Consider the following example.

Example
1. class Student:
2. # Constructor - non parameterized
3. def __init__(self):
4. print("This is non parametrized constructor")
5. def show(self,name):
6. print("Hello",name)
7. student = Student()
8. student.show("John")
Python Parameterized Constructor
The parameterized constructor has multiple parameters along with the self. Consider the
following example.

Example
1. class Student:
2. # Constructor - parameterized
3. def __init__(self, name):
4. print("This is parametrized constructor")
5. self.name = name
6. def show(self):
7. print("Hello",self.name)
8. student = Student("John")
9. student.show()

Output:
This is parametrized constructor
Hello John
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. Consider the
following example.

Example
1. class Student:
2. roll_num = 101

18
3. name = "Joseph"
4. def display(self):
5. print(self.roll_num, self.name)
6. st = Student()
7. st.display()
Output:
101 Joseph
More than One Constructor in Single class
Let's have a look at another scenario, what happen if we declare the two same constructors in
the class.

Example
1. class Student:
2. def __init__(self):
3. print("The First Constructor")
4. def __init__(self):
5. print("The second contructor")
6.
7. st = Student()

Output:
The Second Constructor

In the above code, the object st called the second constructor whereas both have the same
configuration. The first method is not accessible by the st object. Internally, the object of the
class will always call the last constructor if the class has multiple constructors.

Note: The constructor overloading is not allowed in Python.

Python built-in class functions


The built-in functions defined in the class are described in the following table.

SN Function Description

1 getattr(obj, name, default) It is used to access the attribute of the object.

2 setattr(obj, name, value) It is used to set a particular value to the specific


attribute of an object.

3 delattr(obj, name) It is used to delete a specific attribute.

19
4 hasattr(obj, name) It returns true if the object contains some specific
attribute.

Example
1. class Student:
2. def __init__(self, name, id, age):
3. self.name = name
4. self.id = id
5. self.age = age
6. # creates the object of the class Student
7. s = Student("John", 101, 22)
8. # prints the attribute name of the object s
9. print(getattr(s, 'name'))
10. # reset the value of attribute age to 23
11. setattr(s, "age", 23)
12. # prints the modified value of age
13. print(getattr(s, 'age'))
14. # prints true if the student contains the attribute with name id
15. print(hasattr(s, 'id'))
16. # deletes the attribute age
17. delattr(s, 'age')
18. # this will give an error since the attribute age has been deleted
19. print(s.age)

Output:
John
23
True
AttributeError: 'Student' object has no attribute 'age'

Built-in class attributes


Along with the other attributes, a Python class also contains some built-in class attributes which
provide information about the class.

The built-in class attributes are given in the below table.

SN Attribute Description

20
1 __dict__ It provides the dictionary containing the information about the class
namespace.

2 __doc__ It contains a string which has the class documentation

3 __name__ It is used to access the class name.

4 __module__ It is used to access the module in which, this class is defined.

5 __bases__ It contains a tuple including all base classes.

Example
1. class Student:
2. def __init__(self,name,id,age):
3. self.name = name;
4. self.id = id;
5. self.age = age
6. def display_details(self):
7. print("Name:%s, ID:%d, age:%d"%(self.name, self.id))
8. s = Student("John",101,22)
9. print(s.__doc__)
10. print(s.__dict__)
11. print(s.__module__)

Output:
None
{'name': 'John', 'id': 101, 'age': 22}
__main__

Python Inheritance
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. In this section of the tutorial, we will discuss inheritance in
detail.

In python, a derived class can inherit base class by just mentioning the base in the bracket after
the derived class name. Consider the following syntax to inherit a base class into the derived
class.

21
Syntax
1. class derived-class(base class):
2. <class-suite>

A class can inherit multiple classes by mentioning all of them inside the bracket. Consider the
following syntax.

Syntax
1. class derive-class(<base class 1>, <base class 2>, ..... <base class n>):
2. <class - suite>

Example 1
1. class Animal:
2. def speak(self):
3. print("Animal Speaking")
4. #child class Dog inherits the base class Animal
5. class Dog(Animal):
6. def bark(self):
7. print("dog barking")
8. d = Dog()
9. d.bark()
10. d.speak()
Output:

dog barking
Animal Speaking
Python Multi-Level inheritance
Multi-Level inheritance is possible in python like other object-oriented languages. Multi-level
inheritance is archived 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 archived in python.

22
The syntax of multi-level inheritance is given below.

Syntax
1. class class1:
2. <class-suite>
3. class class2(class1):
4. <class suite>
5. class class3(class2):
6. <class suite>
7. .
8. .

Example
1. class Animal:
2. def speak(self):
3. print("Animal Speaking")
4. #The child class Dog inherits the base class Animal
5. class Dog(Animal):
6. def bark(self):
7. print("dog barking")
8. #The child class Dogchild inherits another child class Dog
9. class DogChild(Dog):
10. def eat(self):
11. print("Eating bread...")
12. d = DogChild()
13. d.bark()

23
14. d.speak()
15. d.eat()

Output:

dog barking
Animal Speaking
Eating bread...

Python Multiple inheritance


Python provides us the flexibility to inherit multiple base classes in the child class.

The syntax to perform multiple inheritance is given below.

Syntax
1. class Base1:
2. <class-suite>
3. class Base2:
4. <class-suite>
5. .
6. .
7. .
8. class BaseN:
9. <class-suite>
10. class Derived(Base1, Base2, ...... BaseN):
11. <class-suite>
Example
1. class Calculation1:
2. def Summation(self,a,b):
3. return a+b;
4. class Calculation2:
5. def Multiplication(self,a,b):
6. return a*b;

24
7. class Derived(Calculation1,Calculation2):
8. def Divide(self,a,b):
9. return a/b;
10. d = Derived()
11. print(d.Summation(10,20))
12. print(d.Multiplication(10,20))
13. print(d.Divide(10,20))
Output:
30
200
0.5

The issubclass(sub,sup) method


The issubclass(sub, sup) method is used to check the relationships between the specified
classes. It returns true if the first class is the subclass of the second class, and false otherwise.

Consider the following example.

Example
1. class Calculation1:
2. def Summation(self,a,b):
3. return a+b;
4. class Calculation2:
5. def Multiplication(self,a,b):
6. return a*b;
7. class Derived(Calculation1,Calculation2):
8. def Divide(self,a,b):
9. return a/b;
10. d = Derived()
11. print(issubclass(Derived,Calculation2))
12. print(issubclass(Calculation1,Calculation2))
Output:
True
False
The isinstance (obj, class) method

The isinstance() method is used to check the relationship between the objects and
classes. It returns true if the first parameter, i.e., obj is the instance of the second
parameter, i.e., class.

Consider the following example.

25
Example
1. class Calculation1:
2. def Summation(self,a,b):
3. return a+b;
4. class Calculation2:
5. def Multiplication(self,a,b):
6. return a*b;
7. class Derived(Calculation1,Calculation2):
8. def Divide(self,a,b):
9. return a/b;
10. d = Derived()
11. print(isinstance(d,Derived))
Output:
True
Method Overriding
We can provide some specific implementation of the parent class method in our child class.
When the parent class method is defined in the child class with some specific implementation,
then the concept is called method overriding. We may need to perform method overriding in
the scenario where the different definition of a parent class method is needed in the child class.

Consider the following example to perform method overriding in python.

Example
1. class Animal:
2. def speak(self):
3. print("speaking")
4. class Dog(Animal):
5. def speak(self):
6. print("Barking")
7. d = Dog()
8. d.speak()
Output:
Barking
Real Life Example of method overriding
1. class Bank:
2. def getroi(self):
3. return 10;
4. class SBI(Bank):
5. def getroi(self):

26
6. return 7;
7. class ICICI(Bank):
8. def getroi(self):
9. return 8;
10. b1 = Bank()
11. b2 = SBI()
12. b3 = ICICI()
13. print("Bank Rate of interest:",b1.getroi());
14. print("SBI Rate of interest:",b2.getroi());
15. print("ICICI Rate of interest:",b3.getroi());
Output:
Bank Rate of interest: 10
SBI Rate of interest: 7
ICICI Rate of interest: 8
Data abstraction in python
Abstraction is an important aspect of object-oriented programming. In python, we can
also perform data hiding by adding the double underscore (___) as a prefix to the
attribute which is to be hidden. After this, the attribute will not be visible outside of
the class through the object.

Consider the following example.

Example
1. class Employee:
2. __count = 0;
3. def __init__(self):
4. Employee.__count = Employee.__count+1
5. def display(self):
6. print("The number of employees", Employee.__count)
7. emp = Employee()
8. emp2 = Employee()
9. try:
10. print(emp.__count)
11. finally:
12. emp.display()
Output:
The number of employees 2
AttributeError: 'Employee' object has no attribute '__count'

27
What is Data Hiding?
Data hiding is a part of object-oriented programming, which is generally used to hide the data
information from the user. It includes internal object details such as data members, internal
working. It maintained the data integrity and restricted access to the class member. The main
working of data hiding is that it combines the data and functions into a single unit to conceal
data within a class. We cannot directly access the data from outside the class.

This process is also known as the data encapsulation. It is done by hiding the working
information to user. In the process, we declare class members as private so that no other class
can access these data members. It is accessible only within the class.

Data Hiding in Python


Python is the most popular programming language as it applies in every technical domain and
has a straightforward syntax and vast libraries. In the official Python documentation, Data
hiding isolates the client from a part of program implementation. Some of the essential
members must be hidden from the user. Programs or modules only reflected how we could use
them, but users cannot be familiar with how the application works. Thus it provides security
and avoiding dependency as well.

We can perform data hiding in Python using the __ double underscore before prefix. This
makes the class members private and inaccessible to the other classes.

Let's understand the following example.

Example –

1. class CounterClass:
2. __privateCount = 0
3. def count(self):
4. self.__privateCount += 1
5. print(self.__privateCount)
6. counter = CounterClass()
7. counter.count()
8. counter.count()
9. print(counter.__privateCount)

Output:

1
2
Traceback (most recent call last):
File "<string>", line 17, in <module>

28
AttributeError: 'CounterClass' object has no attribute
'__privateCount'

Advantages of Data Hiding


Below are the main advantages of the data hiding.

o The class objects are disconnected from the irrelevant data.


o It enhances the security against hackers that are unable to access important data.
o It isolates object as the basic concept of OOP.
o It helps programmer from incorrect linking to the corrupt data.
o We can isolate the object from the basic concept of OOP.
o It provides the high security which stops damage to violate data by hiding it from the
public.

Disadvantages of Data Hiding


Every coin has two sides if there are advantages then there will be disadvantage as well. Here
are the some disadvantages are given below.

o Sometimes programmers need to write the extra line of the code.


o The data hiding prevents linkage that act as link between visible and invisible data
makes the object faster.
o It forces the programmers to write extra code to hide the important data from the
common users.

Data hiding is an important aspect when it comes to privacy and security to particularly within
the application. It plays an essential role in preventing unauthorized access. It has some
disadvantages, but these are avoidable in front of its advantages.

What is Overloading?
Overloading, in the context of programming, refers to the ability of a function or an operator
to behave in different ways depending on the parameters that are passed to the function, or the
operands that the operator acts on. In this article, we will see how we can perform function
overloading and operator overloading in Python.

Overloading a method fosters reusability. For instance, instead of writing multiple methods
that differ only slightly, we can write one method and overload it. Overloading also improves
code clarity and eliminates complexity.

Overloading is a very useful concept. However, it has a number of disadvantages associated


with it. Overloading can cause confusion when used across inheritance boundaries. When
used excessively, it becomes cumbersome to manage overloaded functions.
29
Function Overloading in Python
Depending on how the function has been defined, we can call it with zero, one, two, or even
many parameters. This is referred to as "function overloading".

Function overloading is further divided into two types: overloading built-in functions and
overloading custom functions. We will look at both the types in the upcoming sections.

Overloading Built-in Functions


It is possible for us to change the default behavior of Python's built-in functions. We only
have to define the corresponding special method in our class.

Let us demonstrate this using Python's len() function on our Purchase class:

class Purchase:
def __init__(self, basket, buyer):
self.basket = list(basket)
self.buyer = buyer
def __len__(self):
return len(self.basket)
purchase = Purchase(['pen', 'book', 'pencil'], 'Python')
print(len(purchase))

Output:
3

To change how the len() function behaves, we defined a special method named _len_() in our
class. Anytime we pass an object of our class to len(), the result will be obtained by calling
our custom defined function, that is, _len_().

The output shows that we are able to use len() to get the length of the basket.

If we call len() on the object without the __len__() function overloaded, we will get a
TypeError as shown below:

class Purchase:
def __init__(self, basket, buyer):
self.basket = list(basket)
self.buyer = buyer

purchase = Purchase(['pen', 'book', 'pencil'], 'Python')


print(len(purchase))

Output:

Traceback (most recent call last):


File "C:/Users/admin/func.py", line 8, in <module>
print(len(purchase))
TypeError: object of type 'Purchase' has no len()

30
Note: Python expects the len() function to return an integer, hence this should be put into
consideration when overloading the function. If your overloaded function is expected to return
anything else other than an integer, you will get a TypeError.

We can change the behavior of the len() method in the above example from within the
definition of its implementation, that is, __len__(). Instead of returning the length of the basket,
let us make it return something else:

class Purchase:
def __init__(self, basket, buyer):
self.basket = list(basket)
self.buyer = buyer

def __len__(self):
return 10;

purchase = Purchase(['pen', 'book', 'pencil'], 'Python')


print(len(purchase))

Output:
10

Instead of returning the length of the basket, it now returns the value that we have specified.

Overloading User-Defined Functions


To overload a user-defined function in Python, we need to write the function logic in such a
way that depending upon the parameters passed, a different piece of code executes inside the
function. Take a look at the following example:

class Student:
def hello(self, name=None):
if name is not None:
print('Hey ' + name)
else:
print('Hey ')

# Creating a class instance


std = Student()

# Call the method


std.hello()

# Call the method and pass a parameter


std.hello('Nicholas')
Output:

Hey
Hey Nicholas

31
We have created the class Student with one function named hello(). The class takes the
parameter name which has been set to None. This means the method can be called with or
without a parameter.

We have created an instance of the class which has been used to call the function twice, first
with zero parameters and secondly with one parameter. We have implemented function
overloading since there are two ways to call the function.

Operator Overloading in Python


The operator overloading in Python means provide extended meaning beyond their predefined
operational meaning. Such as, we use the "+" operator for adding two integers as well as joining
two strings or merging two lists. We can achieve this as the "+" operator is overloaded by the
"int" class and "str" class. The user can notice that the same inbuilt operator or function is
showing different behaviour for objects of different classes. This process is known as operator
overloading.

Example:

1. print (14 + 32)


2. # Now, we will concatenate the two strings
3. print ("Java" + " Programming")
4. # We will check the product of two numbers
5. print (23 * 14)
6. # Here, we will try to repeat the String
7. print ("X Y Z " * 3)

Output:
46
Java Programming
322
X Y Z X Y Z X Y Z

How to Overload the Operators in Python?


Suppose the user has two objects which are the physical representation of a user-defined data
type class. The user has to add two objects using the "+" operator, and it gives an error. This is
because the compiler does not know how to add two objects. So, the user has to define the
function for using the operator, and that process is known as "operator overloading". The user
can overload all the existing operators by they cannot create any new operator. Python provides
some special functions, or we can say magic functions for performing operator overloading,
which is automatically invoked when it is associated with that operator. Such as, when the user
uses the "+" operator, the magic function __add__ will automatically invoke in the command
where the "+" operator will be defined.

32
How to Perform Binary "+" Operator in Python:
When the user uses the operator on the user-defined data types of class, then a magic
function that is associated with the operator will be invoked automatically. The process
of changing the behaviour of the operator is as simple as the behaviour of the function
or method defined.

The user define methods or functions in the class and the operator works according to
that behaviour defined in the functions. When the user uses the "+" operator, it will
change the code of a magic function, and the user has an extra meaning of the "+"
operator.

Program 1: Simply adding two objects.


Python program for simply using the overloading operator for adding two objects.

Example:

1. class example:
2. def __init__(self, X):
3. self.X = X
4.
5. # adding two objects
6. def __add__(self, U):
7. return self.X + U.X
8. object_1 = example( int( input( print ("Please enter the value: "))))
9. object_2 = example( int( input( print ("Please enter the value: "))))
10. print (": ", object_1 + object_2)
11. object_3 = example(str( input( print ("Please enter the value: "))))
12. object_4 = example(str( input( print ("Please enter the value: "))))
13. print (": ", object_3 + object_4)

Output:

Please enter the value: 23


Please enter the value: 21
: 44
Please enter the value: py
Please enter the value: thon
: python

33
Program 2: defining Overloading operator in another object
Python program for defining the overloading operator inside another object.

Example:

1. class complex_1:
2. def __init__(self, X, Y):
3. self.X = X
4. self.Y = Y
5.
6. # Now, we will add the two objects
7. def __add__(self, U):
8. return self.X + U.X, self.Y + U.Y
9.
10. Object_1 = complex_1(23, 12)
11. Object_2 = complex_1(21, 22)
12. Object_3 = Object_1 + Object_2
13. print (Object_3)

Output:
(44, 34)
Program 3: Overloading comparison operators in Python
Python program for overloading comparison operators.

Example:

1. class example_1:
2. def __init__(self, X):
3. self.X = X
4. def __gt__(self, U):
5. if(self.X > U.X):
6. return True
7. else:
8. return False
9. object_1 = example_1(int( input( print ("Please enter the value: "))))
10. object_2 = example_1(int (input( print("Please enter the value: "))))
11. if(object_1 > object_2):
12. print ("The object_1 is greater than object_2")

34
13. else:
14. print ("The object_2 is greater than object_1")

Output:

Case 1:

Please enter the value: 23


Please enter the value: 12
The object_1 is greater than object_2

Case 2:
Please enter the value: 20
Please enter the value: 31
The object_2 is greater than object_1

Program 4: Overloading equality and less than operators


Python Program for overloading equality and less than operators:

Example:

1. class E_1:
2. def __init__(self, X):
3. self.X = X
4. def __lt__(self, U):
5. if(self.X < U.X):
6. return "object_1 is less than object_2"
7. else:
8. return "object_2 is less than object_1"
9. def __eq__(self, U):
10. if(self.X == U.X):
11. return "Both the objects are equal"
12. else:
13. return "Objects are not equal"
14.
15. object_1 = E_1(int( input( print ("Please enter the value: "))))
16. object_2 = E_1(int( input( print ("Please enter the value: "))))
17. print (": ", object_1 < object_2)
18.

35
19. object_3 = E_1(int( input( print ("Please enter the value: "))))
20. object_4 = E_1(int( input( print ("Please enter the value: "))))
21. print (": ", object_3 == object_4)

Output:
Case 1:
Please enter the value: 12
Please enter the value: 23
: object_1 is less than object_2
Please enter the value: 2
Please enter the value: 2
: Both the objects are equal

Case 2:
Please enter the value: 26
Please enter the value: 3
: object_2 is less than object_1
Please enter the value: 2
Please enter the value: 5
: Objects are not equal
Python magic functions used for operator
overloading:
Binary Operators:
Operator Magic Function

+ __add__(self, other)

- __sub__(self, other)

* __mul__(self, other)

/ __truediv__(self, other)

// __floordiv__(self, other)

% __mod__(self, other)

** __pow__(self, other)

36
>> __rshift__(self, other)

<< __lshift__(self, other)

& __and__(self, other)

| __or__(self, other)

^ __xor__(self, other)

Comparison Operators:
Operator Magic Function

< __LT__(SELF, OTHER)

> __GT__(SELF, OTHER)

<= __LE__(SELF, OTHER)

>= __GE__(SELF, OTHER)

== __EQ__(SELF, OTHER)

!= __NE__(SELF, OTHER)

Assignment Operators:
Operator Magic Function

-= __ISUB__(SELF, OTHER)

+= __IADD__(SELF, OTHER)

*= __IMUL__(SELF, OTHER)

37
/= __IDIV__(SELF, OTHER)

//= __IFLOORDIV__(SELF, OTHER)

%= __IMOD__(SELF, OTHER)

**= __IPOW__(SELF, OTHER)

>>= __IRSHIFT__(SELF, OTHER)

<<= __ILSHIFT__(SELF, OTHER)

&= __IAND__(SELF, OTHER)

|= __IOR__(SELF, OTHER)

^= __IXOR__(SELF, OTHER)

Unary Operator:
Operator Magic Function

- __NEG__(SELF, OTHER)

+ __POS__(SELF, OTHER)

~ __INVERT__(SELF, OTHER)

38
How to do method overriding in Python

Method overriding in Python is when you have two methods with the same name that each
perform different tasks. This is an important feature of inheritance in Python.

In method overriding, the child class can change its functions that are defined by its ancestral
classes. In other words, the child class has access to the properties and functions of the parent
class method while also extending additional functions of its own to the method. If a method
in a superclass coincides with that of a subclass, then the subclass is said to override the
superclass.

There are two prerequisite conditions for Method overriding:

1. Inheritance should be present in the code, method overriding cannot be performed in


the same class, and overriding can only be executed when a child class is derived
through inheritance.

2. The child class should have the same name and the same number of parameters as the
parent class.

Invoking a parent class or child class method depends upon the object being used to invoke.
The reference object determines the execution of an overridden method.

Code
class Animal:
def Walk(self):
print('Hello, I am the parent class')

class Dog(Animal):
39
def Walk(self):
print('Hello, I am the child class')

print('The method Walk here is overridden in the code')

#Invoking Child class through object r

r = Dog()
r.Walk()

#Invoking Parent class through object r

r = Animal()
r.Walk()

40

You might also like