0% found this document useful (0 votes)
13 views20 pages

Python Unit - 5

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views20 pages

Python Unit - 5

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

Leela Soft Python Madhu

Inheritance
Inheritance in Python
 It refers to defining a new class with little or no modification to an existing class.
 The new class is called derived (or child) class and the one from which it inherits is called
the base (or parent) class.
 It provides reusability of a code. We don’t have to write the same code again and again.
Also, it allows us to add more features to a class without modifying it.
 It is transitive in nature, which means that if class B inherits from another class A, then all
the subclasses of B would automatically inherit from class A.

Inheriting Classes in Python


Python Inheritance Syntax
class BaseClass:
Body of base class
class DerivedClass(BaseClass):
Body of derived class

Derived class inherits features from the base class where new features can be added to it. This
results in re-usability of code.

Inheritance is represented using the Unified Modeling Language or UML in the following way:

Classes are represented as boxes with the class name on top. The inheritance relationship is
represented by an arrow from the derived class pointing to the base class. The word extends is
usually added to the arrow.

Example of Inheritance in Python


class Animal:
def speak(self):
print("Animal Speaking")

# child class Dog inherits the base class Animal


class Dog(Animal):
def bark(self):
print("dog barking")

d = Dog()
d.bark()
d.speak()

Page 1 of 20 www.leelasoft.com Cell: 78 42 66 47 66


Leela Soft Python Madhu

Polymorphism in Python
What is Polymorphism: The word polymorphism means having many forms. In programming,
polymorphism means same function name (but different signatures) being uses for different
types.

Example of inbuilt polymorphic functions:


# Python program to demonstrate in-built poly-
# morphic functions

# len() being used for a string


print(len("geeks"))

# len() being used for a list


print(len([10, 20, 30]))

Examples of used defined polymorphic functions:


# A simple Python function to demonstrate
# Polymorphism

def add(x, y, z=0):


return x + y + z

# Driver code
print(add(2, 3))
print(add(2, 3, 4))

Polymorphism with Inheritance:


In Python, Polymorphism lets us define methods in the child class that have the same name as
the methods in the parent class. In inheritance, the child class inherits the methods from the
parent class. However, it is possible to modify a method in a child class that it has inherited from
the parent class. This is particularly useful in cases where the method inherited from the parent
class doesn’t quite fit the child class. In such cases, we re-implement the method in the child
class. This process of re-implementing a method in the child class is known as Method Overriding.

Polymorphism and Method Overriding


This is mostly used in cases where the method inherited from the parent class doesn’t fit the child
class. This process of re-implementing a method in the child class is known as Method Overriding.

Here is an example that shows polymorphism with inheritance:


class Bird:
def intro(self):
print("There are different types of birds")

def flight(self):
print("Most of the birds can fly but some cannot")

Page 2 of 20 www.leelasoft.com Cell: 78 42 66 47 66


Leela Soft Python Madhu
class parrot(Bird):
def flight(self):
print("Parrots can fly")

class penguin(Bird):
def flight(self):
print("Penguins do not fly")

obj_bird = Bird()
obj_parr = parrot()
obj_peng = penguin()

obj_bird.intro()
obj_bird.flight()

obj_parr.intro()
obj_parr.flight()

obj_peng.intro()
obj_peng.flight()

Example
class Animal:
def speak(self):
print("speaking")

class Dog(Animal):
def speak(self):
print("Barking")

d = Dog()
d.speak()

Types of Inheritance
There are five types of inheritance in python:
1. Single Inheritance
2. Multiple Inheritance
3. Multilevel Inheritance
4. Hierarchical Inheritance
5. Hybrid Inheritance

Python Multiple Inheritance


A class can be derived from more than one base class in Python, similar to C++. This is called
multiple inheritance.

In multiple inheritance, the features of all the base classes are inherited into the derived class.

Page 3 of 20 www.leelasoft.com Cell: 78 42 66 47 66


Leela Soft Python Madhu
The syntax for multiple inheritance:
class Base1:
pass

class Base2:
pass

class MultiDerived(Base1, Base2):


pass

Example:
class Calculation1:
def Summation(self, a, b):
return a + b;

class Calculation2:
def Multiplication(self, a, b):
return a * b;

class Derived(Calculation1, Calculation2):


def Divide(self, a, b):
return a / b;

d = Derived()
print(d.Summation(10, 20))
print(d.Multiplication(10, 20))
print(d.Divide(10, 20))

Python Multilevel Inheritance:


We can also inherit from a derived class. This is called multilevel inheritance. It can be of any
depth in Python.

In multilevel inheritance, features of the base class and the derived class are inherited into the
new derived class.

The syntax for multiple inheritance:


class Base:
pass

class Derived1(Base):
pass

class Derived2(Derived1):

Page 4 of 20 www.leelasoft.com Cell: 78 42 66 47 66


Leela Soft Python Madhu
pass

Example:
class Animal:
def speak(self):
print("Animal Speaking")

#The child class Dog inherits the base class Animal


class Dog(Animal):
def bark(self):
print("dog barking")

#The child class Dogchild inherits another child class Dog


class DogChild(Dog):
def eat(self):
print("Eating bread...")

d = DogChild()
d.bark()
d.speak()
d.eat()

Deriving a class from other derived classes that are in turn derived from the same base class is
called multi-path inheritance.

As shown in the above figure, the derived class has two immediate base classes - Derived Class I
and Derived Class 2. Both these base classes are themselves derived from the Base Class, thereby

Page 5 of 20 www.leelasoft.com Cell: 78 42 66 47 66


Leela Soft Python Madhu
forming a grandparent, parent, and child form of a relationship. The derived class inherits the
features of the Base Class (grandparent) via two separate paths. Therefore, the Base Class is also
known as the indirect base class.

Program to demonstrate multi-path inheritance


class Student:
def name(self):
print('Name...')

class AcademicPerformance (Student):


def Acad_score(self):
print("Academic Score...90% and above")

class ECA(Student):
def ECA_score(self):
print('ECA Score......60% and above')

class Result (AcademicPerformance, ECA):


def Eligibility (self):
print("**Minimum Eligibility to Apply**")
self.Acad_score()
self.ECA_score()

R = Result()
R.Eligibility()

Problem in Multi-Path Inheritance (Diamond Problem)


The derived class inherits the members of the base class (grandparent) twice, via parent] (Derived
Class 1) and via parent 2 (Derived Class 2). This results in ambiguity because a duplicate set of
members is created. This ambiguous situation must be avoided.

Thus, we see that diamond relationships exist when at least one of the parent classes can be
accessed through multiple paths from the bottommost class. Diamond relationship is very
common in Python as all classes inherit from the object and in case of multiple inheritance there
is more than one path to reach the object. To prevent, base classes from being accessed more
than once, the dynamic algorithm (C3 and the MRO) linearizes the search order in such a way
that the left-to-right ordering specified in each class is preserved and each parent is called only
once (also known as monotonic).

Method Resolution Order (MRO) in Python:


Every class in Python is derived from the object class. It is the most base type in Python.

So technically, all other classes, either built-in or user-defined, are derived classes and all objects
are instances of the object class.

# Output: True
print(issubclass(list,object))

Page 6 of 20 www.leelasoft.com Cell: 78 42 66 47 66


Leela Soft Python Madhu

# Output: True
print(isinstance(5.5,object))

# Output: True
print(isinstance("Hello",object))

In the multiple inheritance scenario, any specified attribute is searched first in the current class.
If not found, the search continues into parent classes in depth-first, left-right fashion without
searching the same class twice.

Example
class Base1:
pass

class Base2:
pass

class MultiDerived(Base1, Base2):


pass

So, in the above example of MultiDerived class the search order is [MultiDerived, Base1, Base2,
object]. This order is also called linearization of MultiDerived class and the set of rules used to
find this order is called Method Resolution Order (MRO).

MRO must prevent local precedence ordering and also provide monotonicity. It ensures that a
class always appears before its parents. In case of multiple parents, the order is the same as
tuples of base classes.

MRO of a class can be viewed as the __mro__ attribute or the mro() method. The former returns
a tuple while the latter returns a list.

>>> MultiDerived.__mro__
(<class '__main__.MultiDerived'>,
<class '__main__.Base1'>,
<class '__main__.Base2'>,
<class 'object'>)

>>> MultiDerived.mro()
[<class '__main__.MultiDerived'>,
<class '__main__.Base1'>,
<class '__main__.Base2'>,
<class 'object'>]

Here is a little more complex multiple inheritance example and its visualization along with the
MRO.

Page 7 of 20 www.leelasoft.com Cell: 78 42 66 47 66


Leela Soft Python Madhu

# Demonstration of MRO
class X:
pass

class Y:
pass

class Z:
pass

class A(X, Y):


pass

class B(Y, Z):


pass

class M(B, A, Z):


pass

print(M.mro())

# Output:
# [<class '__main__.M'>, <class '__main__.B'>,
# <class '__main__.A'>, <class '__main__.X'>,
# <class '__main__.Y'>, <class '__main__.Z'>,
# <class 'object'>]

Abstract Classes and Interfaces


Abstract Classes:
Abstract classes are classes that contain one or more abstract methods. An abstract method is a
method that is declared, but contains no implementation. Abstract classes may not be
instantiated, and require subclasses to provide implementations for the abstract methods.
Subclasses of an abstract class in Python are not required to implement abstract methods of the
parent class.

Page 8 of 20 www.leelasoft.com Cell: 78 42 66 47 66


Leela Soft Python Madhu

Creating an Abstract class:


Python comes with a module which provides the infrastructure for defining Abstract Base Classes
(ABCs). This module is called - abc.

from abc import ABC

class AbstractClassExample(ABC):
pass

Since an abstract class is an incomplete class, users are not allowed to create its object. To use
such a class, programmers must derive it keeping in mind that they would only be either using or
overriding the features. specified in that class.

Therefore, we see that an abstract class just serves as a template for other classes by defining a
list of methods that the classes must implement. It makes no sense to instantiate an abstract
class because all the method definitions are empty and must be implemented in a subclass.

Interfaces:
The abstract class is thus an interface definition. In inheritance, we say that a class implements
an interface if it inherits from the class which specifies that interface. In Python, we use the
NotImplementedError to restrict the instantiation of a class. Any class that has the
NotImplementedError inside method definitions cannot be instantiated. Consider the
program given in the following example which creates an abstract class Fruit. Two other classes,
Mango and Orange are derived from Fruit that implements all the methods defined in Fruit. Then
we create the objects of the derived classes to access the methods defined in these classes.

Example:
class Fruit:
def taste(self):
raise NotImplementedError()

def rich_in (self):


raise NotImplementedError()

def colour (self):


raise NotImplementedError()

class Mango (Fruit):


def taste(self):
return "Sweet"

def rich_in (self):


return "Vitamin A"

def colour (self):


return "Yellow"

Page 9 of 20 www.leelasoft.com Cell: 78 42 66 47 66


Leela Soft Python Madhu
class Orange (Fruit):
def taste(self):
return "Sour"

def rich_in(self):
return "Vitamin C"

def colour(self):
return "Orange"

Alphanso = Mango()
print(Alphanso.taste(), Alphanso.rich_in(), Alphanso.colour())

Org = Orange()
print (Org.taste(), Org.rich_in(), Org.colour ())

Error and Exception Handling


Introduction to Errors and Exceptions:
 Syntax Errors
 Logic Error
 Exceptions

Syntax Errors:
Syntax errors, also known as parsing errors, are perhaps the most common kind of complaint you
get while you are still learning Python:

Example:
>>> while True print('Hello world')
File "<stdin>", line 1
while True print('Hello world')
^
SyntaxError: invalid syntax

Logic Errors:
Logic errors are those that appear once the application is in use. They are most often faulty
assumptions made by the developer, or unwanted or unexpected results in response to user
actions.

For example, a mistyped key might provide incorrect information to a method, or you may
assume that a valid value is always supplied to a method when that is not the case.

Exceptions:
Even if a statement or expression is syntactically correct, it may cause an error when an attempt
is made to execute it. Errors detected during execution are called exceptions and are not

Page 10 of 20 www.leelasoft.com Cell: 78 42 66 47 66


Leela Soft Python Madhu
unconditionally fatal: we will soon learn how to handle them in Python programs. Most
exceptions are not handled by programs, however, and result in error messages as shown here:

>>> 10 * (1/0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero

>>> 4 + spam*3
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'spam' is not defined

>>> '2' + 2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Can't convert 'int' object to str implicitly

The last line of the error message indicates what happened. Exceptions come in different types,
and the type is printed as part of the message: the types in the example are
ZeroDivisionError, NameError and TypeError. The string printed as the exception type is
the name of the built-in exception that occurred. This is true for all built-in exceptions, but need
not be true for user-defined exceptions (although it is a useful convention). Standard exception
names are built-in identifiers (not reserved keywords).

The rest of the line provides detail based on the type of exception and what caused it.

The preceding part of the error message shows the context where the exception occurred, in the
form of a stack traceback. In general it contains a stack traceback listing source lines;
however, it will not display lines read from standard input.

Handling Exceptions:
It is possible to write programs that handle selected exceptions. Look at the following example,
which asks the user for input until a valid integer has been entered, but allows the user to
interrupt the program (using Control-C or whatever the operating system supports); note that a
user-generated interruption is signaled by raising the KeyboardInterrupt exception.

while True:
try:
x = int(input("Please enter a number: "))
break
except ValueError:
print("Oops! That was no valid number. Try again...")

The try statement works as follows:


 First, the try clause (the statement(s) between the try and except keywords) is executed.

Page 11 of 20 www.leelasoft.com Cell: 78 42 66 47 66


Leela Soft Python Madhu
 If no exception occurs, the except clause is skipped and execution of the try statement is
finished.
 If an exception occurs during execution of the try clause, the rest of the clause is skipped.
Then if its type matches the exception named after the except keyword, the except clause
is executed, and then execution continues after the try statement.
 If an exception occurs which does not match the exception named in the except clause, it
is passed on to outer try statements; if no handler is found, it is an unhandled exception
and execution stops with a message as shown above.

The try with multiple except blocks:


The way of handling exception is varied from exception to exception. Hence for every exception
type a separate except block we have to provide. i.e. try with multiple except blocks is possible
and recommended to use.

Syntax:
try:
Statement 1
Statement 2
except ZeroDivisionError:
Perform alternative
Arithmetic operations
except FileNotFoundError:
Use local file instead of remote file

If try with multiple except blocks available then based on raised exception the corresponding
except block will be executed.

Example:
try:
x = int(input("Enter First Number: "))
y = int(input("Enter Second Number: "))
print(x / y)
except ZeroDivisionError :
print("Can't Divide with Zero")
except ValueError:
print("please provide int value only")

If try with multiple except blocks available, then the order of these except blocks is important.
Python interpreter will always consider from top to bottom until matched except block
identified.

Example:
try:
x = int(input("Enter First Number: "))
y = int(input("Enter Second Number: "))
print(x / y)
except ArithmeticError :
print("ArithmeticError")

Page 12 of 20 www.leelasoft.com Cell: 78 42 66 47 66


Leela Soft Python Madhu
except ZeroDivisionError:
print("ZeroDivisionError")

Multiple Exceptions in a Single Block:


We can write a single except block that can handle multiple different types of exceptions.

Syntax:
except (Exception1,Exception2,exception3,..):
or
except (Exception1,Exception2,exception3,..) as msg :

Parenthesis are mandatory and this group of exceptions internally considered as tuple.

Example:
try:
x = int(input("Enter First Number: "))
y = int(input("Enter Second Number: "))
print(x / y)
except (ZeroDivisionError, ValueError) as msg:
print("Plz Provide valid numbers only and problem is: ", msg)

finally block:
It is not recommended to maintain clean up code (Resource De-allocating Code or Resource
releasing code) inside try block because there is no guarantee for the execution of every
statement inside try block always.

It is not recommended to maintain clean up code inside except block, because if there is no
exception then except block won't be executed.

Hence we required some place to maintain clean up code which should be executed always
irrespective of whether exception raised or not raised and whether exception handled or not
handled. Such type of best place is nothing but finally block.

Hence the main purpose of finally block is to maintain clean up code.

Syntax:
try:
Risky Code
except:
Handling Code
finally:
Cleanup code

The specialty of finally block is it will be executed always whether exception raised or not raised
and whether exception handled or not handled.

Case-1: If there is no exception


try:

Page 13 of 20 www.leelasoft.com Cell: 78 42 66 47 66


Leela Soft Python Madhu
print("try")
except:
print("except")
finally:
print("finally")

Output
try
finally

Case-2: If there is an exception raised but handled:


try:
print("try")
print(10 / 0)
except ZeroDivisionError:
print("except")
finally:
print("finally")

Output
try
except
finally

Case-3: If there is an exception raised but not handled:


try:
print("try")
print(10 / 0)
except NameError:
print("except")
finally:
print("finally")

Output
try
finally
ZeroDivisionError: division by zero (Abnormal Termination)

The else Clause


In some situations, you might want to run a certain block of code if the code block inside try ran
without any errors. For these cases, you can use the optional else keyword with the try
statement.

Note: Exceptions in the else clause are not handled by the preceding except clauses.

Example:
# program to print the reciprocal of even numbers
try:

Page 14 of 20 www.leelasoft.com Cell: 78 42 66 47 66


Leela Soft Python Madhu
num = int(input("Enter a number: "))
assert num % 2 == 0
except:
print("Not an even number!")
else:
reciprocal = 1 / num
print(reciprocal)

Raising Exceptions
 As a Python developer you can choose to throw an exception if a condition occurs.
 To throw (or raise) an exception, use the raise keyword.

Syntax: raise [Exception [, args [, traceback]]]

Example:
Raise an error and stop the program if x is lower than 0:

x = -1

if x < 0:
raise Exception("Sorry, no numbers below zero")

Example:
 The raise keyword is used to raise an exception.
 We can define what kind of error to raise, and the text to print to the user.

x = "hello"

if not type(x) is int:


raise TypeError("Only integers are allowed")

Built- in Exceptions
In Python, all exceptions must be instances of a class that derives from BaseException. In a try
statement with an except clause that mentions a particular class, that clause also handles any
exception classes derived from that class.

The built-in exceptions can be generated by the interpreter or built-in functions. Except where
mentioned, they have an “associated value” indicating the detailed cause of the error. This may
be a string or a tuple of several items of information (e.g., an error code and a string explaining
the code). The associated value is usually passed as arguments to the exception class’s
constructor.

The built-in exception classes can be subclassed to define new exceptions; programmers are
encouraged to derive new exceptions from the Exception class or one of its subclasses, and
not from BaseException.

Page 15 of 20 www.leelasoft.com Cell: 78 42 66 47 66


Leela Soft Python Madhu
Some of the Built- in Exceptions
Exception Name Description
BaseException The base class for all built-in exceptions. It is not meant to be
directly inherited by user-defined classes (for that, use
Exception).
Exception All built-in, non-system-exiting exceptions are derived from this
class. All user-defined exceptions should also be derived from this
class.
ArithmeticError The base class for those built-in exceptions that are raised for
various arithmetic errors: OverflowError, ZeroDivisionError,
FloatingPointError.
LookupError The base class for the exceptions that are raised when a key or
index used on a mapping or sequence is invalid: IndexError,
KeyError.
AttributeError Raised when an attribute reference or assignment fails
EOFError Raised when the input() function hits an end-of-file condition
(EOF) without reading any data.
ImportError Raised when the import statement has troubles trying to load a
module
ModuleNotFoundError A subclass of ImportError which is raised by import when a module
could not be located.
IndexError Raised when a sequence subscript is out of range.
KeyError Raised when a mapping (dictionary) key is not found in the set of
existing keys.

User defined Exceptions


 Also known as Customized Exceptions or Programmatic Exceptions
 Some time we have to define and raise exceptions explicitly to indicate that something
goes wrong, such type of exceptions is called User Defined Exceptions or Customized
Exceptions.

Programmer is responsible to define these exceptions and Python not having any idea about
these. Hence we have to raise explicitly based on our requirement by using "raise" keyword.

How to Define and raise Customized Exceptions:


 Every exception in Python is a class that extends Exception class either directly or
indirectly.

Syntax:
class classname(predefined_exception_class_name):
def __init__(self,arg):
self.msg=arg

Example:
class TooYoungException(Exception):
def __init__(self, arg):
self.msg = arg

Page 16 of 20 www.leelasoft.com Cell: 78 42 66 47 66


Leela Soft Python Madhu

class TooOldException(Exception):
def __init__(self, arg):
self.msg = arg

age = int(input("Enter age: "))


if age > 60:
raise TooYoungException("Please wait some more time defenitelly
you will get best match soon")
elif age < 18:
raise TooOldException("Your age already crossed marriage age no
chance of getting marriage")
else:
print('Thanks for registration you will get maatch datils soon..by
mail')

Example 2:
class SalaryNotInRangeError(Exception):
"""Exception raised for errors in the input salary.

Attributes:
salary -- input salary which caused the error
message -- explanation of the error
"""

def __init__(self, salary, message="Salary is not in (5000, 15000)


range"):
self.salary = salary
self.message = message
super().__init__(self.message)

salary = int(input("Enter salary amount: "))


if not 5000 < salary < 15000:
raise SalaryNotInRangeError(salary)

Note:
The raise keyword is best suitable for customized exceptions but not for pre defined
exceptions

Concept of Operator Overloading


With operator overloading, a programmer is allowed to provide his own definition for an
operator to a class by overloading the built-in operator. This enables the programmer to perform
some specific computation when the operator is applied on class objects and to apply a standard
definition when the same operator is applied on a built-in data type.

This means that while evaluating an expression with operators, Python looks at the operands
around the operator. If the operands are of built-in types, Python calls a built-in routine. In case,

Page 17 of 20 www.leelasoft.com Cell: 78 42 66 47 66


Leela Soft Python Madhu
the operator is being applied on user-defined operand(s), the Python compiler checks to see if
the programmer has an overloaded operator function that it can call. If such a function whose
parameters match the type(s) and number of the operands exists in the program, the function is
called, otherwise a compiler error is generated.

Advantage of Operator Overloading


We can easily write our Python programs without the knowledge of operator overloading, but
the knowledge and use of this feature can help us in many ways. Some of them are:
• With operator overloading, programmers can use the same notations for user-defined
objects and built-in objects. For example, to add two complex numbers, we can simply
write C1 + C2.
• With operator overloading, a similar level of syntactic support is provided to user-defined
types as provided to the built-in types.
• In scientific computing where computational representation of mathematical objects is
required, operator overloading provides great ease to understand the concept.
• Operator overloading makes the program clearer. For example, the statement
(C1.mul(C2).div(C1.add(C2)) can be better written as C1 * C2 / C1 + C2

Implementing Operator Overloading:


Program to add two complex numbers without overloading the + operator
class Complex:
def __init__(self):
self.real = 0
self.imag = 0
def setValue(self, real, imag):
self.real = real
self.imag = imag
def display(self):
print("(", self.real, " + ", self.imag, "i)")

C1 = Complex()
C1.setValue(1, 2)

C2 = Complex()
C2.setValue(3, 4)

C3 = Complex()
C3 = C1 + C2
C3.display()

OUTPUT:
TypeError: unsupported operand type(s) for +: 'instance' and 'instance'

So, the reason for this error is simple. + operator does not work on user-defined objects. Now, to
do the same concept, we will add an operator overloading function in our code.

Page 18 of 20 www.leelasoft.com Cell: 78 42 66 47 66


Leela Soft Python Madhu
For example, look at the code given below which has the overloaded add function specified as
__add__().

Program to overload the + operator on a complex object


class Complex:
def __init__(self):
self.real = 0
self.imag = 0
def setValue(self, real, imag):
self.real = real
self.imag = imag
def __add__(self, C):
Temp = Complex()
Temp.real = self.real + C.real
Temp.imag = self.imag + C.imag
return Temp
def display(self):
print("(", self.real, " + ", self.imag, "i)")

C1 = Complex()
C1.setValue(1, 2)
C2 = Complex()
C2.setValue(3, 4)
C3 = Complex()
C3 = C1 + C2
print("RESULT = ")
C3.display()

In the program, when we write C1 + C2, the __add__() function is called on C1 and C2 is passed
as an argument. Remember that, user-defined classes have no + operator defined by default. The
only exception is when you inherit from an existing class that already has the + operator defined.

Note: The __add__() method returns the new combined object to the caller

Operators and their corresponding function names:


Operator Function Name Operator Function Name
+ __add__ += __iadd__
- __sub__ -= __isub__
* __mul__ *= __imul__
/ __truediv__ /= __idiv__
** __pow__ **= __ipow__
% __mod__ %= __imod__
>> __rshift__ >>= __irshift__
& __and__ &= __iand__
| __or__ |= __ior__
^ __xor__ ^= __ixor__
~ __invert__ ~= __iinvert__
<< __lshift__ <<= __ilshift__

Page 19 of 20 www.leelasoft.com Cell: 78 42 66 47 66


Leela Soft Python Madhu
> __gt__ <= __le__
< __lt__ == __eq__
>= __ge__ != __ne__

The program given below compares two Book objects. Although the class Book has three,
attributes, comparison is done based on its price. However, this is not mandatory. You can
compare two objects based on any of the attributes.

Program to compare two objects of user-defined class type:


class Book:
def __init__(self):
title = ""
publisher = ""
price = 0
def set(self, title, publisher, price):
self.title = title
self.publisher = publisher
self.price = price
def display(self):
print("TITLE : ", self.title)
print("PUBLISHER : ", self.publisher)
print("PRICE : ", self.price)
def __gt__(self, B):
if self.price > B.price:
return True
else:
return False

B1 = Book()
B1.set("OOP with C++", "Oxford University Press", 525)
B2 = Book()
B2.set("Let us C++", "BPB", 300)
if B1 > B2:
print("This book has more knowledge so I will buy")
B1.display()

Page 20 of 20 www.leelasoft.com Cell: 78 42 66 47 66

You might also like