UNIT: V Object Oriented Programming Lectures:
08 Hrs
• Programming Paradigms-monolithic, procedural, structured and object oriented ,
• Features of Object oriented programming:
• classes, objects, methods and message passing, inheritance,
polymorphism,
containership, reusability, delegation, data abstraction and encapsulation
• Classes and Objects:
• classes and objects, class method and self object,
• class variables and object variables,
• public and private members, class methods.
Savitribai Phule Pune University
Programming Paradigm:
Programming paradigm is an approach to solve problem using
some programming language.
There are lots for programming language that are known but all
of them need to follow some strategy when they are
implemented and this methodology/strategy is paradigms.
Various programming paradigms are
1. Monolithic Programming
2. Procedural Programming
3. Structural Programming
4. Object Oriented Programming
Savitribai Phule Pune University
1. Monolithic Programming:
The Program which contains a single function for the large
program is called monolithic program.
A program is not divided into parts
When program size increases it also increase difficulty.
The program is sequential code and variable used is global
data.
goto statement is used for specific jump or flow control
statement.
Savitribai Phule Pune University
Advantages:
Easy to implement programs for small applications.
Disadvantages:
If the program size is large then it is difficult to check error.
Due to single function, the program is difficult to maintain.
Code cannot be reused as it is written for specific problem.
Savitribai Phule Pune University
2. Procedural Programming
Procedural programming is a programming paradigm that uses
a linear or top-down approach.
It relies on functions (procedures or subroutines) to perform
computations.
Procedural programming is also known as imperative
programming.
Large programs are divided into smaller programs known as
functions.
Function access the global data.
Top down approach
Savitribai Phule Pune University
Advantages:
Simple and easy to write.
These language have low memory utilization.
Disadvantages:
Parallel programming is not possible.
Difficult to maintain programs.
Less productive.
Savitribai Phule Pune University
3. Structural Programming:
Also known as modular programming.
The structured program mainly consist of
1. Selection Statements (if, if…else, if….elif…else statements)
2. Sequence Statements
3. Iteration Statements (loops- for, while)
The program consist of structured and separate modules.
Example: C, Pascal
Savitribai Phule Pune University
Advantages:
Program is easy to implement and maintain.
Programs are problem based not the machine based.
Disadvantages:
Conversion of program to machine code takes time.
Savitribai Phule Pune University
4. Object Oriented Programming:
The program is written as a collection of classes and object
which are meant for communication.
The smallest and basic entity is object and all kind of
computation is performed on the objects only.
Data and function are grouped into one entity called class.
Programs are divided into classes and member functions.
Savitribai Phule Pune University
Advantages:
Importance is given to data.
Bottom up Approach
Data is hidden and can not be accessed
by external functions.
Disadvantages:
Complex to implement.
Savitribai Phule Pune University
Difference between procedure oriented language and object oriented language.
Sr Procedural Oriented
Object oriented language
No. Language
Importance is given to
1 Importance is given to data
algorithm
2 Top down appraoch Bottom Up Approach
Programs are divided into
3 Programs are divided into objects
functions
Data is hidden and can not be
4 Data is not hidden
accessed by external functions
private, public, protected access
5 no access specifier
specifier is used.
6 less secure more secure
7 Example: C, Pascal Example: C++, Java
Savitribai Phule Pune University
Features of Object oriented programming:
1. Class:
class is a collection of objects.
It is a logical entity that has data members and methods
(member functions).
Once class has been defined, we can create any number of
objects belonging to that class.
Ex: Mango, Apple and Orange are the members of Fruit class.
Syntax:
class classname:
Ex:
class Fruit:
Savitribai Phule Pune University
2. Object:
Object is an instance of class. The object is an entity that has state and
behavior.
It may be any real-world object like the person, place, bank account or
any item etc.
Everything in Python is an object.
Syntax:
objectname = classname( )
Ex:
obj = Fruit( )
Savitribai Phule Pune University
Sr Class Object
No.
1 Class is collection of
objects. Class is collection
An object is instance of a class.
of data members and
member functions.
2 Class is a logical entity. Object is a physical entity.
3 Class is declared once. Object is created many times.
4 Class doesn't allocated
Object allocates memory when it
memory when it is
is created.
created.
5 Ex: Object: Apple, Banana,
Ex: Class: Fruit
Mango, Guava
Savitribai Phule Pune University
3. Method:
The method is a function that is associated with an object.
There must be a special first argument self in all of method definitions.
Any object type can have methods.
There is usually a special method called __init__ ( )in most classes.
Savitribai Phule Pune University
4. Message Passing:
Objects communicate with one another by sending and receiving
information to each other.
A message for an object is a request for execution of a procedure and
therefore will invoke a function (procedure) in the receiving object that
generates the desired results.
Message passing involves specifying the name of the object, the name
of the function and the information to be sent.
Ex: employee.salary(name)
Savitribai Phule Pune University
5. Inheritance:
Inheritance is the process by which object of one class acquires
properties object of another class.
reusability concept is used.
Sub Class: The class that inherits properties from another class is called
Sub class or Derived Class.
Super Class/ Base class: The class whose properties are inherited by
sub class is called Base Class or Super class.
Example: Dog, Cat, Cow can be Derived Class of Animal Base Class.
Savitribai Phule Pune University
6. Polymorphism:
Ability to perform more than one forms.
An operation may exhibit different behaviors in different instances.
The behavior depends upon the types of data used in the operation.
Savitribai Phule Pune University
7. Containership:
one class contain the object of another class.
This type of relationship between classes is known as containership or
has a relationship.
The class which contains the object and members of another class in
this kind of relationship is called a container class.
Ex: 1) computer system has a hard disk
2) car has an Engine, chassis, steering wheels.
Savitribai Phule Pune University
8. Reusability:
The child class inherits some behaviour of parent class.
For child class, it is not necessary to write code for inherited behavior,
i.e. child class directly used the methods written in parent class.
For instance, the class Student inherits Person class. Hence the method
such as getName( ), getAddress( ) of parent class Person can be
directly used by the Student class. The Student class can have its own
additional method such as getMarks( ).
Thus methods can be written once and can be reused.
Savitribai Phule Pune University
9. Composition & Delegation:
This is feature of object oriented programming by which one class
depends upon the other class.
It is represented by has a relationship.
In composition – The child cannot exist if parent class is not present i.e.
child class depends on parent class. It is strong relationship.
In delegation there is dependency of one class on another but even if
the parent class is not present the dependent class exists.
Ex: A teacher may belong to multiple departments. So, Teacher is a part
of multiple departments. But lets say if we “delete” a Department, the
Teacher will still be there. This is delegation.
A school can contain multiple classrooms. Now if we “delete” the
school, the classrooms will automatically be deleted. This is
composition.
Savitribai Phule Pune University
10. Data Abstraction and Encapsulation:
1. Data abstraction
Data abstraction means representing only essential features by hiding all
the implementation details.
Class is entity used for data abstraction.
The methods are defined in class. From main function we can access
these functionalities using objects.
2. Encapsulation
Encapsulation means binding of data and methods in single
entity called class.
The data inside the class is accessible by the function in same class.
Public and Private access specifier is used for data protection
It is normally not accessible from outside of the component.
Savitribai Phule Pune University
Savitribai Phule Pune University
Sr Data abstraction Data encapsulation
No.
Representing only essential
binding of data and methods in
1 features by hiding all the
single entity called class.
implementation details.
It is used in software design It is used in software
2
phase. implementation phase.
encapsulation using Access
abstraction using Abstract
3 Modifiers (Public, Protected &
Class.
Private.)
Depends on object data
4 independent on object data type.
type.
Focus mainly on what Focus primarily on how it should
5 should be done. be done.
Savitribai Phule Pune University
Terminologies used in object oriented Programming
1. Class: class is collection of data members and member functions. To
define class, use class keyword.
2. Data member: the variable used in class holds data associated with
class and its object of that class.
3. Method (member function): It is one type of function defined inside
the class definition.
4. Object: Instance of class. Object can access both data members and
member function.
5. Instantiation: creation of instance of class or object.
Savitribai Phule Pune University
Classes and Objects:
1. Class:
class is a collection of objects.
It is a logical entity that has data members and methods (member
functions).
Once class has been defined, we can create any number of objects
belonging to that class.
Ex: Mango, Apple and Orange are the members of Fruit class.
Savitribai Phule Pune University
Syntax:
class classname:
statement 1 #Data members and Member functions
statement 2
statement 3
Ex:
class Student:
rollno = 101 # Data members
name = "Priya"
def fun(self):
print('Hello') # Member Functions
Savitribai Phule Pune University
2. Object:
Object is an instance of class.
The object is an entity that has state and behavior.
It may be any real-world object like the person, place, bank account or
any item etc.
Everything in Python is an object.
Syntax:
objectname = classname( )
Ex:
obj = Student( )
Savitribai Phule Pune University
Class Method and self object:
The class methods are the function defined inside the class.
The class method defines the first argument as self. This is always
defined as the first argument.
If there is no argument in class method then only self is the argument
for that method.
The self argument refers to object itself.
Savitribai Phule Pune University
Program using class and object:
class Student:
rollno = 101
name = "Priya"
def fun(self):
print('Hello')
obj = Student( )
print("Roll Number is :",obj.rollno) #Accessing data using
print("Name of student is :",obj.name) # object of class
obj.fun( ) #Accessing method using object
Output:
Roll Number is : 101
Name of student is : Priya
Hello
Savitribai Phule Pune University
The __init__( ) Method (Constructor)
The __init__() method is automatically executed when an object of a
class is created.
The __init__() method is a known as a constructor method in Python.
The method is useful to initialize the variables of class object.
Note that __init__( )is prefixed as well as suffixed by double
underscores.
The __init__( )method can be declared as,
Syntax:
def __init__(self, variables):
statement1
statement2
Savitribai Phule Pune University
Ex:
class ABC():
def __init__(self, val):
print("In class method.....")
self.val = val
print("The value is: ", val)
obj = ABC(10)
Output:
In class method.....
The value is: 10
Savitribai Phule Pune University
The __del__( ) method:
The __del__() method is a known as a destructor method in
Python.
The __del__()method is automatically called when an object is
going out of scope.
Savitribai Phule Pune University
class ABC:
count = 0 #class variable
def __init__(self, var):
ABC.count += 1
self.var = var #object variable
print("The Object value is: ", var)
print("The value of class variable is: ", ABC.count)
def __del__(self):
print("Object value %d is out of scope" %self.var)
obj1 = ABC(10)
obj2 = ABC(20)
obj3 = ABC(30)
del obj1
del obj2
del obj3
Savitribai Phule Pune University
Output:
The Object value is: 10
The value of class variable is: 1
The Object value is: 20
The value of class variable is: 2
The Object value is: 30
The value of class variable is: 3
Object value 10 is going out of scope
Object value 20 is going out of scope
Object value 30 is going out of scope
Savitribai Phule Pune University
1. Write a python program to find area of rectangle using class.
class rect:
def __init__(self ,length, breadth):
self.length=length
self.breadth=breadth
def get_area(self):
return self.length*self.breadth
r=rect(160,120)
print("Area of rectangle:",(r.get_area()))
Output:
Area of rectangle:19200
Savitribai Phule Pune University
Class Variables and object variables
1. Class variable
The variables at the class level are called class variables.
The class variables are shared by all the instances of the class i.e. same
value is used for every instance or object
There is single copy of class variable which is shared among all the
objects, hence changes made by an object in a single copy of class
variable is reflected in all other objects.
2. Object Variable
The variable owned by each object is called object variable.
For each object or instance of class, the instance variables are different.
Object variables are defined in methods.
The changes made in one object variable will not be reflected for other
object variable.
Savitribai Phule Pune University
class ABC:
count = 0 #class variable
def __init__(self, var):
ABC.count += 1
self.var = var #object variable
print("The Object value is: ", var)
print("The value of class variable is: ", ABC.count)
obj1 = ABC(10)
obj2 = ABC(20)
obj3 = ABC(30)
Output:
The Object value is: 10
The value of class variable is: 1
The Object value is: 20
The value of class variable is: 2
The Object value is: 30
The value of class variable is: 3
Savitribai Phule Pune University
Public and private members:
Public variables are those variables that are defined in the class and can be
accessed from within class and from outside the class using dot operator.
All members in a python class are public by default.
Private variables are those variables that are defined in the class but can
be accessible by the methods of that class only.
The private variables are used with double underscore( __ ) prefix.
Savitribai Phule Pune University
class ABC:
def __init__(self, var1, var2):
self.var1 = var1
self.__var2 = var2
def display(self):
print("From class method, variable 1 is: ", self.var1)
print("From class method, variable 2 is: ",
self.__var2)
obj = ABC(10,20)
obj.display()
print("From class method, variable 1 is: ", obj.var1)
print("From class method, variable 2 is: ", obj.__var2)
Output:
From class method, variable 1 is: 10
From class method, variable 2 is: 20
From class method, variable 1 is: 10
Traceback (most recent call last)
---> 13 print("From class method, variable 2 is: ", obj.__var2)
AttributeError: 'ABC' object has no attribute '__var2'
Savitribai Phule Pune University
To remove above error, to access private variable use
following syntax:
objectname._classname__privatevariable
Ex:
print("From class method, variable 2 is: ",obj._ABC__var2)
Savitribai Phule Pune University
To access private method, use following syntax:
objectname._classname__privatemethodname
Ex:
class ABC:
def __init__(self, var):
self.__var = var
def __display(self):
print("From class method,variable is:",
self.__var)
obj = ABC(10)
obj._ABC__display()
Output:
From class method, variable is: 10
Savitribai Phule Pune University
To call class method from another class method
class ABC:
def __init__(self, var):
self.var = var
def display(self):
print("From class method,variable is:", self.var)
def add(self):
self.var += 2
self.display()
obj = ABC(10)
obj.add()
Output:
From class method, variable is: 12
Savitribai Phule Pune University
Class Methods
A class method is a method that is bound to class rather than its object. It does not require
creation of class instance.
The @classmethod decorator is used for class method definition.
Syntax:
@classmethod
def functionname(cls, arguments..):
statement1
statement2
Savitribai Phule Pune University
Ex:
class Test:
count = 0
def __init__(self):
Test.count += 1
@classmethod
def greeting(cls):
print("Welcome from class: %s" %cls.count)
Test.greeting()
Output:
Welcome from class
Savitribai Phule Pune University
Write a program in python to Create class EMPLOYEE for storing details (Name,
Designation, gender, Date of Joining and Salary). Define function members to display all
EMPLOYEE details.
class Employee:
name = []
designation = []
gender = []
doj = []
salary = []
def __init__(self):
for i in range(3):
self.name.append(input("Enter the name:"))
self.designation.append(input("Enter the Designation:"))
self.gender.append(input("Enter the gender:"))
self.doj.append(input("Enter the doj:"))
self.salary.append(int(input("Enter the salary:")))
Savitribai Phule Pune University
def display(self):
print("-------------Details of Employee-----------------")
print(" Name\t\tDesignation\tGender\t\tDate of Joining\t\
tSalary ")
print("-------------------------------------------------")
for i in range(3):
print(self.name[i],"\t\t",self.designation[i],"\t",
self.gender[i],"\t\t",self.doj[i],"\t\t",self.salary[i] )
e = Employee()
e.display()
Output:
Enter the name:Sakshi
Enter the Designation:Manager
Enter the gender:Male
Enter the doj:10-06-2001
Enter the salary:50000
Savitribai Phule Pune University
Enter the name:Rohit
Enter the Designation:Developer
Enter the gender:Male
Enter the doj:10-05-2009
Enter the salary:35000
Enter the name:Riya
Enter the Designation:Tester
Enter the gender:Female
Enter the doj:10-02-2012
Enter the salary:20000
----------------------Details of Employee--------------------------
Name Designation Gender Date of Joining Salary
-------------------------------------------------------------------
Sakshi Manager Male 10-06-2001 50000
Rohit Developer Male 10-05-2009 35000
Riya Tester Female 10-02-2012 20000
Savitribai Phule Pune University