Python Programming S.Y.
-II E&TC
Unit 04:
Object Oriented Programming
(OOP) in Python
✓ Classes and Objects
✓ Methods, Constructor Method
✓ Inheritance, Overriding Methods
✓ Error and Exception
✓ Exception Handling
Prof. R. R. Shriram
Dept. of E&TC Engg.
Programming Paradigms
• Paradigm is the principle by which a program is organized to
perform a given task.
• Structured programming paradigm means breaking down a
given task into smaller tasks, writing functions for each task
and carrying out interaction of these functions.
• Object-Oriented programming paradigm means creation and
interaction of objects.
• Python supports both Structured as well as Object-Oriented
programming paradigms.
Prof. R. R. Shriram
Classes
• A Class is a blueprint/design.
• A Class bundles data and functionality together.
(Class)
Appliances
(Object 1) (Object 2)
Mobile Laptop
Prof. R. R. Shriram
Objects
• Everything is an Object in Python.
• Every Object has an Attribute and Behavior.
(Class)
Appliances
(Object 1) (Object 2)
Mobile Laptop
Battery=5000mAh send_message() Battery=4400mAh run_software()
Clock=2.2Ghz make_calls() Clock=3.2Ghz save_files()
(Attributes) (Behavior) (Attributes) (Behavior)
Objects
• Everything is an Object in Python.
• Every Object has an Attribute (i.e., Data) and Behavior (i.e.,
Method).
• When an object of a class is created, i.e., an instance of the class is
created and the class is said to be instantiated.
• In principle, every object has instance data (i.e., attribute) and
instance methods (i.e., behavior).
• In practice, every object has instance data (i.e., attribute) whereas
methods (i.e., behavior) are shared amongst objects.
• A single class may have any number of instances (i.e., objects).
Prof. R. R. Shriram
Classes and Objects
• Hence, Class – Design
Object - Instance
• Programmatic examples of classes and objects are:
a=2 #a is an object of int class
b = 3.56 #b is an object of float class
c = ‘Hello’ #c is an object of str class
d = [1, 2, 3, 4] #d is an object of list class
e = (‘a’, 1, 2) #e is an object of tuple class
• Note that int, float, str, list, tuple are built-in classes in Python.
Prof. R. R. Shriram
Classes and Objects
• Apart from using Python library’s built-in classes, we can create
our own classes called as User-defined data types (Classes).
• A user-defined class Employee may contain data like name, age,
salary and methods like store_data(), display_data( ) to store and
display employee data.
• From a user-defined class Employee, objects such as emp1, emp2
are created. Creation of an object is called as instantiation and
the data in an object is called attribute.
Prof. R. R. Shriram
Classes and Objects
(Class)
Employee
(Object 1) (Object 2)
emp1 emp2
name=‘abc’ store_data() name=‘xyz’ store_data()
age=20 display_data() age=30 display_data()
salary=10000 salary=20000
(Behavior) (Behavior)
(Attributes) (Attributes)
Prof. R. R. Shriram
Creating a Class
• To create a class, use the syntax is-
class ClassName:
Statement 1
.
.
.
Statement N
• Example- Create a class named DemoClass:
class DemoClass:
x=5
Prof. R. R. Shriram
Creating an Object
• Objects can be created using syntax-
objectname = ClassName()
• Example- Create an object named p1, and print the value
of x:
class DemoClass: #creating a class named DemoClass
x=5 #Class variable
p1 = DemoClass() #creating an object named p1
print(p1.x) #printing value of x using object p1
Prof. R. R. Shriram
Class and Objects
Q1.Create a class named Operation, create a method named
addition() inside the class to perform addition of two numbers.
Print the result of addition.
A1.
class Operation:
def addition(self):
a=2
b=3
c=a+b
print(c)
m1=Operation()
m1.addition() Prof. R. R. Shriram
Explanation of previous example
• Here we have created a class named Operation and one method
named addition().
• m1=Operation() creates a nameless object and stores its address
in m1.
• Methods of the class can be called using the syntax
object.method() i.e., m1.addition().
Prof. R. R. Shriram
self variable
• Whenever we call a method using an object, address of the object
gets passed to the method implicitly. This address is collected by
the method in a variable called self.
• So, instance methods must have an extra first parameter in the
method definition. We do not give a value for this parameter when
we call the method, Python provides it.
• If we have a method that takes no arguments, then also we have
to have one argument which can be named as self or any other
valid name can be used.
• This is similar to this pointer in C++ and this reference in Java.
Prof. R. R. Shriram
Class and Objects
Q2.Create a class named Operation, create a method inside the
class named addition() which accepts two values to perform
addition of two numbers. Print the result of addition.
A2.
class Operation:
def addition(self,a,b):
c=a+b
print(c)
obj=Operation()
obj.addition(2,3)
Prof. R. R. Shriram
Class and Objects
Q3.Create a class named Employee, create two methods
inside the class named store_data() to store employee data
and display_data() to print employee data. Create two
objects emp1 and emp2 and access both the methods of the
class.
Prof. R. R. Shriram
A3. Class and Objects
class Employee:
def store_data(self,n,a,s):
self.name=n
self.age=a
self.salary=s
def display_data(self):
print(self.name,self.age,self.salary)
emp1=Employee()
emp1.store_data(‘Mira’,20,20000)
emp1.display_data()
emp2=Employee()
emp2.store_data(‘Avi’,30,20000)
emp2.display_data()
Prof. R. R. Shriram
Instance Variables and Class Variables
• Instance variables are variables whose value is assigned inside a
constructor or method with self.
• Instance variables are accessed using syntax- self.variable
• Instance variables are specific to an object.
• Changing value of instance variable will not be reflected to other
objects.
Prof. R. R. Shriram
Example
class demo: Output:
def f1(self): hello
self.name=‘hello’ hello
print(self.name) abc
p1=demo() hello
p1.f1()
p2=demo() • From this example, it can be observed that,
p2.f1() changing the value of a instance variable
p1.name=‘abc’ by using ClassName.variable=value has
print(p1.name) changed value only of the specific object
print(p2.name) and the changes are not reflected to all
objects.
Prof. R. R. Shriram
Instance Variables and Class Variables
• Class variables are variables whose value is assigned in the class
without prepending them with self.
• Class variables are accessed using syntax- ClassName.variable or
object.variable.
• Class variables are shared by all objects and are not related to a
specific object.
• Changing value by using ClassName.variable=value will be
reflected to all the objects.
• Class variables are like static members in C++/Java.
Prof. R. R. Shriram
class Demo: Example
x=5
c1=Demo()
c2=Demo()
print(c1.x) • From this example, it can be observed that,
print(c2.x) changing the value of a class variable by using
Demo.x=10 ClassName.variable=value has reflected the
print(c1.x) changes to all objects.
print(c2.x)
Output:
5
5
10
10
Prof. R. R. Shriram
Instance Methods and Class Methods
• Instance methods are methods in which first argument received
is self followed by other arguments. If an Instance method does
not receive any arguments then also it has one self argument.
• Instance methods are accessed using the syntax-
object.methodname().
• Class methods are methods which do not receive self argument.
• Class methods are accessed using the syntax-
ClassName.methodname().
• Class methods are like static members in C++/Java.
Prof. R. R. Shriram
Example
class Demo:
count=0 #Class Variable
def f1(self,n): #Instance Method
self.name=n #Instance Variable
print(self.name) #Accessing Instance Variable
def f2(): #Class Method
Demo.count+=1
print(Demo.count) #Accessing Class Variable
m1=Demo()
m1.f1(‘Amit’) #Accessing Instance Method
Demo.f2() #Accessing Class Method
Prof. R. R. Shriram
Public and Private Members of Class
• Members of a class (data and methods) are accessible from outside
the class.
• It is a good idea to keep data in a class inaccessible from outside
the class and access it through member functions of the class.
• Private members by convention start with an underscore.
• Eg.: _name, _age, _salary.
• Strongly Private members by convention start with a double
underscore.
• Eg.: __name, __age, __salary.
Prof. R. R. Shriram
Constructor Method
• Class functions that begin with double underscore __ are called
special functions as they have special meaning.
• Of one particular interest is the __init__() function. This special
function gets called whenever a new object of that class is
instantiated.
• This type of function is also called constructor in Object
Oriented Programming (OOP).
• It is normally used to initialize all the variables.
Prof. R. R. Shriram
Constructor Method
• When an object is created, space is allocated in memory and
__init__() is called. So address of object is passed to __init__().
• __init__() does not return any value.
• __init__() is called only once during entire lifetime of an object.
• If we do not define __init__() , then Python provides a default
__init__() method.
Prof. R. R. Shriram
Constructor Method
• Example-
class demo:
def __init__(self,n=‘ ’,a=0):
print(n,a)
def f1(self,n,a):
self.name=n
self.age=a
print(self.name,self.age)
p1=demo()
p1.f1(‘Mira’,20)
Prof. R. R. Shriram
Error and Exceptions
• While creating and executing a Python program things may go
wrong at two different stages-during compilation and during
execution.
• Errors that occur during compilation are called Syntax Errors.
• Errors that occur during execution are called Exceptions.
• Hence, there are two types of Errors that can occur-
1. Syntax errors
2. Logical errors (Exceptions)
Prof. R. R. Shriram
Syntax Error
• When the proper syntax of the language is not followed then a
syntax error is thrown.
• It is reported by Interpreter/Compiler.
• It can be corrected by correcting the syntax.
• Example-
• It returns a syntax error message because after the if statement
a colon: is missing.
Prof. R. R. Shriram
Exceptions
• During runtime when an error occurs after passing the syntax
test is called an Exception or logical type of error.
• For example, when we divide any number by zero then the
ZeroDivisionError exception is raised, or when we import a
module that does not exist then ImportError is raised
• Example-
a=2
c=a/0
print(c)
Prof. R. R. Shriram
Exception Handling
• Exceptions in Python are reported by Python Runtime.
• try and except blocks are used to deal with an exception.
• Statements which you suspect may go wrong at runtime should
be enclosed within a try block.
• If while executing statement(s) in try block, an exceptional
condition occurs then it can be tackled in two ways:
a) Pack exception information in an object and raise an
exception.
b) Let Python Runtime pack exception information in an object
and raise an exception.
Prof. R. R. Shriram
Exception Handling
• Two ways to create exception objects:
a) From ready-made exception classes (like ZeroDivisonError).
b) From user-defined exception classes.
• How Python facilitates exception handling:
a) By providing keywords try, except, else, finally, raise.
b) By providing readymade exception classes.
Prof. R. R. Shriram
try-except
• When a program encounters an exception during execution, it is
terminated if the exception is not handled.
• In Python, try-except blocks can be used to catch and respond
to one or multiple exceptions.
• try block- Enclose the code that you anticipate will cause an
exception.
• except block- Catch the raised exception in it. It must
immediately follow the try block.
Prof. R. R. Shriram
try-except
• First try clause is executed i.e. the code
between try and except clause.
• If there is no exception, then only try clause will
run, except clause will not get executed.
• If any exception occurs, the try clause will be skipped
and except clause will run.
• If any exception occurs, but the except clause within the code
doesn’t handle it, it is passed on to the outer try statements. If
the exception is left unhandled, then the execution stops.
• A try statement can have more than one except clause.
Prof. R. R. Shriram
try-except
• Example-
try:
a=int(input(‘Enter an integer:’))
b=int(input(‘Enter an integer:’))
c=a/b
print(c)
except ZeroDivisionError:
print(‘Denominator is 0’)
Output:
Prof. R. R. Shriram
Handling multiple Exceptions
• A try clause can have any number of except clauses to handle
different exceptions, however, only one will be executed in case
an exception occurs.
• We can use a tuple of values to specify multiple exceptions in
an except clause.
• By handling multiple exceptions, a program can respond to
different exceptions without terminating it.
Prof. R. R. Shriram
try-except
• Example 1- Same code block for Multiple exceptions.
try:
a=int(input(‘Enter an integer:’))
b=int(input(‘Enter an integer:’))
c=a/b
print(c)
except (ZeroDivisionError, ValueError) as error:
print(error)
Output: Output:
Enter an integer:2 or Enter an integer:2
Enter an integer:0 Enter an integer:f
division by zero invalid literal for int() with base 10: 'f'
Prof. R. R. Shriram
try-except
• Example 2- Different code blocks for Multiple exceptions.
try:
a=int(input(‘Enter an integer:’))
b=int(input(‘Enter an integer:’))
c=a/b
print(c)
except ZeroDivisionError as ze:
print(ze)
except ValueError as ve:
Output:
print(ve)
Enter an integer:2
except TypeError as te:
Enter an integer:f
print(te)
invalid literal for int() with base 10: 'f'
Prof. R. R. Shriram
else Block
• The try-except statement may also have an optional else
block.
• If it is present it must appear after all the except blocks.
• Control goes to else block if no exception occurs during
execution of the try block.
Prof. R. R. Shriram
else Block
• Example-
try: Output 1:
a=int(input(‘Enter an integer:’)) Enter an integer:3
b=int(input(‘Enter an integer:’)) Enter an integer:4
c=a/b 0.75
print(c) Division successful.
except ZeroDivisionError: or
print(‘Denominator is 0’) Output 2:
else: Enter an integer:2
print(‘Division successful.’) Enter an integer:0
Denominator is 0
Prof. R. R. Shriram
finally Block
• finally block is optional.
• Code in finally always runs no matter what! Even if a
break or return occurs first.
• finally block is placed after except blocks (if they exist).
• try block must have except block and/or finally block.
• finally block is commonly used for releasing external
resources like files, connections or database connections,
irrespective of whether the use of the resource was
successful or not.
Prof. R. R. Shriram
finally Block
• Example 1-
try: Output 1:
a=int(input(‘Enter an integer:’)) Enter an integer:2
b=int(input(‘Enter an integer:’)) Enter an integer:4
c=a/b 0.5
print(c) Program execution ends.
except ZeroDivisionError: or
print(‘Denominator is 0’) Output 2:
finally: Enter an integer:2
print(‘Program execution ends.’) Enter an integer:0
Denominator is 0
Program execution ends.
Prof. R. R. Shriram
try-except-else-finally Block
• Example 2- Output 1:
try: Enter an integer:2
a=int(input(‘Enter an integer:’)) Enter an integer:4
b=int(input(‘Enter an integer:’)) 0.5
c=a/b Division successful.
print(c) Program execution ends.
except ZeroDivisionError: or
print(‘Denominator is 0’) Output 2:
else: Enter an integer:2
print(‘Division successful.’) Enter an integer:0
finally: Denominator is 0
print(‘Program execution ends.’) Program execution ends.
Prof. R. R. Shriram
try-except-else-finally Block
• try: This block will test the expected error to occur.
• except: Here you can handle the error.
• else: If there is no exception then this block will be
executed.
• finally: finally block always gets executed either exception
is generated or not.
Prof. R. R. Shriram
User-defined Exceptions
• Since all exceptional conditions cannot be anticipated, for
every exceptional condition there cannot be a class in
Python library.
• In such cases we can define our own exception class called
as user-defined exceptions.
Prof. R. R. Shriram
class NumberTooSmall(Exception):
def __init__(self,n): User-defined Exceptions
self.num=n
class NumberTooLarge(Exception): Output 1:
def __init__(self,n):
self.num=n Enter a number: 2
class Operations:
def compare(self,n):
Comparison successful.
self.num=n
or
if self.num<0:
raise NumberTooSmall(self.num)
Output 2:
elif self.num>100: Enter a number: -12
raise NumberTooLarge(self.num)
else: Number is smaller than 0.
print(‘Comparison successful.’)
or
c=Operations()
try:
Output 2:
x=int(input(‘Enter a number:’)) Enter a number: 202
c.compare(x)
except NumberTooSmall: Number is greater than 0.
print(‘Number is smaller than 0.’)
except NumberTooLarge:
print(‘Number is greater than 100.’) Prof. R. R. Shriram
Inheritance
• Inheritance is the capability of one class to derive or inherit
the properties from another class.
• The benefits of inheritance are:
1. It represents real-world relationships well.
2. It provides reusability of a code. Instead of reinventing the
same code that is already available, the same code can be
reused by inheritance. Also, it allows us to add more features to
a class without modifying it.
3. 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.
Prof. R. R. Shriram
Inheritance
• In inheritance, a new class called derived class can be
created to inherit features of an existing class called base
class.
• Base class is also called as super class or parent class.
• Derived class is also called as sub class or child class.
Prof. R. R. Shriram
What is accessible where?
• Derived class members can access base class members but vice-
versa is not true.
• In C++ there are private, protected and public keywords to
control the access of base class members from derived class or
from outside the class hierarchy.
• Python does not have any such keywords.
Prof. R. R. Shriram
What is accessible where?
• Effect of private, protected and public is achieved by following a
convention while creating variable names as follows:
var- treat this as public variable
_var- treat this as protected variable
__var- treat this as private variable
• Public variables may be accessed from anywhere.
• Protected variables should be accessed only in class hierarchy.
• Private variables should be used only in the class in which they
are defined.
Prof. R. R. Shriram
What is accessible where?
• Effect of private, protected and public is achieved by following a
convention while creating variable names as follows:
var- treat this as public variable
_var- treat this as protected variable
__var- treat this as private variable
• Note that using _var outside the class hierarchy is only a
convention. If you violate it won’t get errors but it would be a bad
practice to follow.
• However, any attempt to use __var either in the class hierarchy or
outside the class, it would result in an error.
Prof. R. R. Shriram
class Person: Inheritance
def __init__(self, n, a):
self.name = n Output:
self.age = a Mira 25
def printname(self): Welcome Mira from year 2005
print(self.name, self.age)
class Student(Person):
def __init__(self,n,a,y):
#super() function will make the child class inherit all the
super().__init__(n,a) methods and properties from its parent.
self.year=y
def welcome(self):
print(‘Welcome’,self.name,‘from year’,self.year)
s=Student(‘Mira’,25,2005)
s.printname()
s.welcome()
Prof. R. R. Shriram
Inheritance
• In Example 1, Person is the base class and Student is the
derived/inherited class.
• Base class Person is created having two properties name and age
and one method printname().
• A child class named Student is created which inherits the
properties i.e., name and age and method i.e., printname() from
the base class Person. It also has its own property year and method
welcome().
• Now the derived/inherited class Student has the same properties
and method as base class Person as well as its own properties and
method.
Prof. R. R. Shriram
Types of Inheritance
• There are 3 types of Inheritance:-
1. Single Inheritance-
When a child class inherits from only one parent class, it is
called single inheritance.
2. Multi-level Inheritance-
When there is child and grandchild relationship.
3. Multiple Inheritance-
When a child class inherits from multiple parent classes, it is
called multiple inheritance.
Prof. R. R. Shriram
Programs on Types of Inheritance
• Find the programs on different types of
inheritance in the pdf named “Programs on Types
of Inheritance” attached under Unit 04 Tab in
Python Programming Google Classroom.
Prof. R. R. Shriram
Method Overriding
• Method overriding is an ability of any object-oriented
programming language that allows a subclass or child class
to provide a specific implementation of a method that is
already provided by one of its super-classes or parent
classes.
• When a method in a subclass has the same name, same
parameters or signature and same return type(or sub-type)
as a method in its super-class, then the method in the
subclass is said to override the method in the super-class.
• Method overriding can only be done in derived class.
Prof. R. R. Shriram
Method Overriding
• The version of a method that is executed will be determined
by the object that is used to invoke it.
• If an object of a parent class is used to invoke the method,
then the version in the parent class will be executed, but if
an object of the subclass is used to invoke the method, then
the version in the child class will be executed.
• In other words, it is the type of the object being referred to
(not the type of the reference variable) that determines
which version of an overridden method will be executed.
Prof. R. R. Shriram
class Parent:
Method Overriding
def __init__(self):
self.text = ‘Inside Parent class’
def display(self):
print(self.text)
class Child(Parent):
def __init__(self):
Parent.__init__(self)
self.text = ‘Inside Child class’
def display(self):
print(self.text) Output:
c=Child()
Inside Child class
c.display()
p=Parent()
Inside Parent class
p.display() Prof. R. R. Shriram
Method Overriding vs Method Overloading
Method Overriding:
• It is the redefinition of base class function in its derived
class with same signature i.e., return type and parameters.
• It can only be done in derived class.
Prof. R. R. Shriram
Method Overriding vs Method Overloading
Method Overloading in other languages C++, Java etc:
• It provides multiple definitions of the function by changing
signature i.e., changing number of parameters, change
datatype of parameters, return type.
• It can be done in base as well as derived class.
• Unlike many other languages like C++, Java etc., Python
does not support method overloading. It means method
names in a program, or method names within a class must
be unique.
Prof. R. R. Shriram
Thank You!!