Unit 5 Python Programming
Unit 5 Python Programming
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.
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.
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
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.
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")
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
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
6
try:
a=10/0;
except(ArithmeticError, IOError):
print("Arithmetic Exception")
else:
print("Successfully Done")
Output:
Arithmetic Exception
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.
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.
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:
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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
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.
SN Function Description
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'
SN Attribute Description
20
1 __dict__ It provides the dictionary containing the information about the class
namespace.
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...
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
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.
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.
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.
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.
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.
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'
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.
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.
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
Output:
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;
Output:
10
Instead of returning the length of the basket, it now returns the value that we have specified.
class Student:
def hello(self, name=None):
if name is not None:
print('Hey ' + name)
else:
print('Hey ')
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.
Example:
Output:
46
Java Programming
322
X Y Z X Y Z X Y Z
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.
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:
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:
Case 2:
Please enter the value: 20
Please enter the value: 31
The object_2 is greater than object_1
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)
| __or__(self, other)
^ __xor__(self, other)
Comparison Operators:
Operator Magic Function
== __EQ__(SELF, OTHER)
!= __NE__(SELF, OTHER)
Assignment Operators:
Operator Magic Function
-= __ISUB__(SELF, OTHER)
+= __IADD__(SELF, OTHER)
*= __IMUL__(SELF, OTHER)
37
/= __IDIV__(SELF, OTHER)
%= __IMOD__(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.
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')
r = Dog()
r.Walk()
r = Animal()
r.Walk()
40