Complete Unit 5 OOP Notes SPPU

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 60

Unit- V

Object Oriented Programming

By-
Ms. Swati M. Suryawanshi
Introduction
Program- program is collection of instructions that tells the
computer how to solve a particular problem.

Programming language- it is specifically designed to express


computations that can be performed by a computer.

Programming languages are used to create programs that


control the behaviour of system.

Evaluation of Programming Languages


Structural OOP
Procedural
Monolithic Programming Programming
Programming
Programming
Programming Paradigm

• Programming paradigm is fundamental style of programming


that defines how the structure and basic elements of a
computer program will be built.

• The style of writing program, set of capabilities and


limitations that programming language has depends on the
programming paradigm it supports.

• Programming paradigm classified as follows-

1. Monolithic Programming-emphasizes on finding solution


2. Procedural Programming-gives stress on algorithms
3. Structured Programming-focuses on modules
4. Object Oriented Programming-emphasizes on classes and
objects.
Monolithic Programming
Procedural Programming
• Program is divided into n number of
subroutines that access global data to
avoid repetition each subroutine performs
a well defined task.

• Subroutine can call another subroutine.

• Therefore, with ‘jump’, ‘Go To’, and ‘call’


instructions, the sequence of execution of
instructions can be altered.

• FORTRAN and COBOL are two


popular procedural
programming languages.
Procedural Programming

Advantages
• The only goal is to write correct programs.
• Programs were easier to write as compared to monolithic
programming.
Disadvantages
• Writing programs is complex.
• No concept of reusability.
• Requires more time and effort to write programs.
• Programs are difficult to maintain.
• Global data is shared and therefore may get altered (mistakenly).
Structured Programming
• It uses top-down methodology of programming.
• The principle idea behind structured programming is as simple as the
idea of divide and conquer.
• A computer program can be thought of as consisting of a set of tasks.
• Any task that is too complex to be described simply would be broken
down into a set of smaller component tasks, until the tasks were
sufficiently small and self-contained enough that they were easily
understood. C, Pascal are the example of Structured Programming .

• Example- computing the average salary of every employee of a


company is a rather complex task.You can, break it down into these
subtasks/modules

1. Find out what each person earns.


2. Count how many people you have.
3. Total all the salaries.
4. Divide the total by the number of people you have
Structured Programming

Structured programming, also referred to as modular programming.


Advantages
Efficient, correct programs that are easy to understand, debug and
change.
• Modules enhance programmer’s productivity.
Many programmers can work on a single, large program
• A structured program takes less time to be written than other
programs. • Each module performs a specific task.
• Each module has its own local data.
Disadvantages
• Not data-centered.
• Global data is shared and therefore may get inadvertently modified.
• Main focus on functions.
Object Oriented Programming
Difference between Procedure Programming and
Object Oriented Programming
Advantages / Merits of OOP Languages
• Elimination of redundant code through inheritance (by extending existing classes).
• Higher productivity and reduced development time due to reusability of the existing modules.
• Secure programs as data cannot be modified or accessed by any code outside the class.
• Real world objects in the problem domain can be easily mapped objects in the program.
• A program can be easily divided into parts based on objects.
• The data-centered design approach captures more details of a model in a form that can be easily
implemented.
• Programs designed using OOP are expandable as they can be easily upgraded from small to large systems.
• Message passing between objects simplifies the interface descriptions with external systems.
• Software complexity becomes easily manageable.
• With polymorphism, behavior of functions, operators, or objects may vary depending upon the
circumstances
• Data abstraction and encapsulation hides implementation details from the external world.
• OOP enables programmers to write easily extendable and maintainable programs.
• OOP supports code reusability to a great extent. 12
Disadvantages / Demerits of OOP Languages
Programs written using object oriented languages have greater processing overhead as they demand
more resources.
• Requires more skills to learn and implement the concepts.
• Beneficial only for large and complicated programs.
• Even an easy to use software when developed using OOP is hard to be build.
• OOP cannot work with existing systems.
• Programmers must have a good command in software engineering and programming methodology.

13
Applications of OOP Languages

• Designing user interfaces such as work screens, menus, windows, and so on.
• Real-time systems • Simulation and modelling
• Compiler design • Client server system
• Object oriented databases • Object oriented distributed database
• Parallel programming • Decision control systems
• Office automation systems • Hypertext and hypermedia
• Computer-aided design (CAD) systems • Computer animation • Computer-
aided manufacturing (CAM) systems
• Developing computer games
• Artificial intelligence—expert systems and neural networks
• Networks for programming routers, firewalls, and other devices

14
Features of OOP

1. Class- Logical Identity, Blueprint or Template


2. Object-real world entity, instance of class having identity and behaviour
3. Inheritance- On class aquire properties of other class,
baseclass , subclass
4. Polymorphism- Same method with many forms
5. Abstraction-Show only essential details and hide background details.
6. Encapsulation- Packing of data and function in sigle unit. e.g. class
7. Method and Message Passing- objects communicates via message
passing.
8. Containership-Class contains other class’s object as a data member.
9. Reusability- re-use code in same class or in other class
10.Delegation-One object depends on other object for functionality
Classes, Objects
⚫ A class is used to describe something in the world, such as
occurrences, things, external entities, and so on.
⚫A class provides a template or a blueprint thatdescribes the
structure and behavior of a set of similar objects.
⚫Once we have the definition for a class, a specific instance of the class can be
easily created.
⚫Example: class student:
⚫A class can have multiple instances or objects.
⚫Objects are created as: object-name = class-name( )
⚫Example: stud= student ( )
⚫Every object contains some data and procedures. They are also called methods.
Methods and Message Passing
⚫A method is a function associated with a class.
⚫ It defines the operations that the object can execute when it receives a
message.
⚫In OOP language, only methods of the class can access and manipulate the
data stored in an instance of the class (or object).
⚫ Two objects can communicate with each other through messages. An
object asks another object to invoke one of its methods by sending it a
message.
Inheritance
⚫ Inheritance is a concept of OOP in which a new class is created from an existing class.
The new class, often known as a sub-class, contains the attributes and methods of the
parent class
⚫ The new class, known as sub-class or derived class, inherits the attributes and behavior
of the pre-existing class, which is referred to as super-class or parent class.
⚫ The inheritance relationship of sub- and super classes generates a hierarchy. Therefore,
inheritance relation is also called ‘is-a’ relation. A sub-class not only has all the states
and behaviors associated with the super-class but has other specialized features
(additional data or methods) as well.
Inheritance
⚫ The main advantage of inheritance is the ability to reuse the code. When we want a
specialized class, we do not have to write the entire code for that class from scratch. We
can inherit a class from a general class and add the specialized code for the sub- class.
Polymorphism
⚫What is Polymorphism: The word polymorphism means having many forms.
⚫In programming, polymorphism means the same function name (but
different signatures) being used for different types..
Containership and Reusability
⚫Containership is the ability of a class to contain object(s) of one or more
classes as member data.
⚫ For example, class One can have an object of class Two as its data
member. This would allow the object of class One to call the public
functions of class Two. Here, class One becomes the container, whereas
class Two becomes the contained class. Containership is also called
composition.

⚫Reusability means developing codes that can be reused either in the same
program or in different programs.
⚫Python gives due importance to building programs that are reusable.
⚫Reusability is attained through inheritance, containership, and
polymorphism.
Delegation
• Delegation can be an alternative to inheritance.

• Delegation means that you use an object of another class as an instance


variable, and forward messages to the instance.

• Delegation can be viewed as a relationship between objects where one object


forwards certain method calls to another object, called its delegate.

• Provides maximum flexibility to programmers and allow them to generate


reusable code.

• In delegation more than one object is involved in handling a request. The


object that receives the request for a service, delegates it to another object
called its delegate.

• The primary advantage of delegation is run-time flexibility – the delegate


can easily be changed at run-time. 
Data Abstraction and Encapsulation
• Data abstraction: Data abstraction and encapsulation both are often used as
synonyms. Both are nearly synonyms because data abstraction is achieved
through encapsulation.

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

• Data encapsulation, also called data hiding, is the technique of packing data
and functions into a single component (class) to hide implementation details of
a class from the users.

• Users are allowed to execute only a restricted set of operations (class methods)
on the data members of the class.

• Therefore, encapsulation organizes the data and methods into a structure that
prevents data access by any function (or method) that is not specified in the
class.
Class in python
A class is used to describe something in the world. Class
provides template or a blueprint that describes the structure
and behaviour of set of similar objects.

Example- class student


it having attributes roll number, name, course and
aggregate.
Operation can be perform on this getdata(), setdata(),
editdata()
Data and set of operations are applicable to all students
i.e. object of that class.
Example of class

class student:
def init (self,rollno,name,course):
self.rollno=rollno
self.name=name
self.course=course
def showdata(self):

print(self.rollno)
print(self.name)
print(self.course)
Object
Instance of a class called as object.
Object is physical entity

Example
If student is a class , then all 67 students in a
course, all are objects of student class

Hence we can have multiple instances of a class


Every object contains some data and
functions(methods)
Syntax for object

Create object

objname=classname()
● Call variable and methods from class
● objectname.variablename
● objectname.methodname
Example of class and object

class student: #class


def __init__ (self,name,marks): #parameterised
constructor self.name=name
self.marks=marks
def msg(self): #instance method
print(self.name," got ",self.marks)
s1=student("Abcd",30) #create object and calls init method
s2=student("Pqrs",25) #create object and calls init method
s1.msg() #call instance method using object s1
s2.msg() #call instance method using object s2
OUTPUT-
Abcd got 30
Pqrs got 25
Methods in class and self object
• method is a function defined in the class.
• methods must have the first argument named as self.
• This first argument added to the beginning of the parameter list.
You do not pass value for this parameter when you call the
• method.
Python provides it value automatically.
• The self argument refers to the object itself. i.e. objects that has
• called the method.
If you have method which takes no arguments, then you still have
• to define the method to have a self argument. Methods uses self,
they require an object or instance of the class to be used.
• Method with self argument refer as instance method.


The _ _init_ _() method/class constructor
• The init () method is automatically executed when an object of a class
is created.

• The method is useful to initialize the variables of the class object.

• It is also called as class constructor.


init () method which take only self as a parameter called as default
constructor. i.e. No parameter init() method except self.

init () method which take parameter two or more parameter called as
parameterized constructor.

init () method prefix as well as suffixed by double underscores.

• Syntax for init() method


def __init__ (self,arg1,arg2…..):
statements to execute
The del () method/ Destructor

init () method initialize an object when it is created.

The del () method delete these object and free the memory occupied by
them.

The del () method automatically called when an object is going out of scope
or there is no any reference to the object.

This is the time when an object will no longer be used and free the resources
occupied by object.

It is destructor which destroys the object.

del () method is invoked when object is about to destroy.

You can explicitly do the same thing using the del keyword.

Syntax-
def del (self):
statement to execute
Example of del () method / Destructor

class student:
def __init__(self,name,marks):
self.name=name self.marks=marks
def msg(self):
print(self.name," got ",self.marks)
def del(self):
print("Object destroyed")
s1=student("abcd",30)

s2=student("pqrs",25) OUTPUT-
abcd got 30
s1.msg() pqrs got 25
s2.msg() Object destroyed
Object
destroyed
Methods in a class

1. Instance methods
2. Class Methods
3. Static Methods
Instance Method

Instance methods are most common type of methods

in python classes.
● Instance methods must have self as a parameter.
● No decorator needed for instance method.
● Each object having its own instance method.
Instance methods are called using object and dot


operator.
● Syntax to create instance method-
def
methodname(self,arg1,arg2,ar
g3......) Statements to execute
Example of Instance Method

class student:
def init(self,name,marks): #parameterised constructor
self.name=name
self.marks=marks
def msg(self): #instance method
print(self.name," got ",self.marks)
s1=student("Abcd",30)

s2=student("Pqrs",25)
s1.msg() #call instance method using
object s1 s2.msg() #call instance method using
object s2
OUTPUT-
Class Methods

Class methods are different from ordinary methods.

Class methods are called by using class name.

First argument of the class method is cls

Class methods are widely used for factory methods. Factory

methods return class object for different use. Class methods

are marked with a classmethod decorator. Class method

clalled using class name and dot operator Syntax to create

class method-

@classmethod
def methodname(cls,arg2,arg3,….):
statements to execute
●Syntax to call class method-
Classname.methodname(val1,val2,....)


Example of class methods
class myclass:
@classmethod
def calculate(cls,price):
cls.cost=price+10
return cls.cost

obj=myclass() #object created


c=myclass.calculate(495) #calls class method print(c)
print(myclass.cost) #access variable using class name
print(obj.cost) #access variable using object

Output-
505
505
505
Static methods

Static methods are special case of methods.

Any functionality that belongs to class, but that does not require the
object is placed in the static method.

Static method does not receive any additional arguments.


Static methods are just like normal function that belongs to a class.

Static method does not use self & cls as a parameter. Static
method defined using a built-in decorator named @staticmethod.

Python uses decorator to make it easier to apply staticmethod
function to the method function definition.

● Syntax to create static methods-

@staticmethod
def methodname(arg1,arg2,arg3,….):
statements to execute
Example for static method

class Person:
def init (self):
print(“in python constructor init method”)
@staticmethod
def hello():
print(“Hello static method code”)
obj=Person() #calls init method
Person.hello() #static method called with class name

Output-
in python constructor init method
Hello static method code
Class variables and object/instance variables

• Class can have variables defined in it.

• These variables are of two types-


1. Class variable
2. Object variable/instance variable
• Class variables are owned by class

• Object variables owned by object


Class Variables

• Class variables are own by class.

• If a class has one class variable, then there will be one copy only
for that variable.

• All the object of that class will share the class variable.

• There exists a single copy of the class variable, any change made to
the class variable by an object will be reflected in all other
objects.
Object/instance Variables

• Object variables own by object

• Each object has its own object variable.

• If a class has n objects, then there will be n separate copies of the


object variables.

• The object variable is not shared between objects.

• A change made to the object variable by one object will not be


reflected in other objects.
Each time when object created
Class variable value increase by 1
Public and Private data members
• Data members are variable and methods declared and defined in a
class.

• There are two types of data members in a class-


1. Public data members
2. private data members

● Public data members are accessible in class and outside class also.
● Private data members are accessible in a class only. Not outside the
class.
Public data members
• Public variables and methods are those variables and methods
that are defined in the class and can be accessed from anywhere
in the program using dot operator.
• Public variables and methods can be accessed from within class
as well as from outside the class in which it is defined.
Public data members can be called with class name as well as
• object name.
Example of public variable-

class Student:
collegename=”Avcoe” # public class variable
def show(self,division): #public instance method
self.division=division #public instance variable
print(self.division, Student.collegename)
s1=Student()
s1.show(”FE-G”) #FE-G Avcoe
print(Student.collegename) # Avcoe
print(s1.division) #FE-G
print(s1.collegename) # Avcoe
print(Student.division) #FE-G
Private data members
• Private variables are defined in the class with double underscore
prefix(_ _).

• Private variables can be accessed only from within a class.

• Private members are not directly accessible from outside the


class.
• We can call private data members in other method of same class.

If for some reason you can access private variables outside the class
• using object name and class name.

• Syntax to access private variables outside the class-


Objectname._classname privatevariablename
Example of Private data members
class Student:
collegename=”Avcoe” # public class variable
mobileno=1234567890 #private variable
def show(self,division): #public instance method
self.division=division #public instance variable
print(Student. mobileno,
Student.collegename,self.division)
s1=Student()
s1.show(“FE-G”) #1234567890 Avcoe
print(s1.collegename)
#Avcoe print(Student.division)
#FE-G
# print(Student. mobileno) Error private var not accessible outside
# print(s1.__mobileno) #Error private var not accessible outside
Calling one method from another method
● We can call a class method from another method of same class by
using the self.
● Example-
class Abc:
def init
(self,var):
self.var=var
def display(self):
print(“var is= “,self.var)
def add(self):
self.var=self.var+2
self.display() #calling method in another method
obj=Abc(10)
obj.add()

Output-
var is = 12
Encapsulation

you can restrict access to methods class Car:
and variables. def init (self):

This can prevent the data from self. updateSoftware()
being modified by accident and is
known as encapsulation. def drive(self):

Encapsulation is restricted print('driving')
accesss to methods or variables.

Encapsulation prevents from def updateSoftware(self):
accessing accidentally, but not print('updating
intentionally. software')

Example:-
redcar = Car()


redcar.drive()
#redcar. updateSoftware() not
accesible from object.
Inheritance

Re--usability is an important feature of oop.

It save efforts and cost required to build software product

It enhances its reliability.

Python allows its programmers to create new classes that re-use the pre-

written code.
The technique of creating a new class from an existing class is called
● inheritance
The old or existing class is called the base class and new class is known as

the derived class or subclass.

The derived classes are created by first inheriting the data and methods of
the base class and then adding the new specialized data and function in

Syntax of inheritance
it. Inheritance uses is-aintype
Python
of relationship.

class DerivedClass(BaseClass):
class Account: Example of inheritance
def init (self, name, acct_num): Withdrawing amount for 1001

self.name = name Depositing amount for 1001


Scheduling appointment for


self.acctnum = acctnum

1001
def withdraw(self, amount):
print('Withdrawing amount for ', self.acctnum)
def deposit(self, amount):
print('Depositing amount for ', self.acctnum)
class Bussinessaccount(Account):
def scheduleAppointment(self):
print('Scheduling appointment for ', self.acctnum)

obj = Bussinessaccount('Sushil', 755) #Bussinessaccount child


class object
obj.withdraw(1000) # withdraw method inherited from Account
class obj.deposit(5000) #deposit method inherited from Account
class obj.scheduleAppointment() # calls method from child class


In the example, object of PrivilegedAccount is created since it has inherited the methods of the Super class
so withdraw and deposit methods can be called on the PrivilegedAccount class object.
Abstraction

Abstraction means hiding the complexity and only showing
the essential features of the object.

Abstraction is hiding the real implementation

User is knowing only how to use it.

Abstraction in Python is achieved by using abstract classes
and interfaces.

An abstract class is a class that generally provides

incomplete functionality and contains one or more abstract
methods.
● Abstract methods are the methods that generally don’t have
any implementation.

It is left to the sub classes to provide implementation for


the abstract methods.
@abstractmethod decorator is required for abstract
methods Real world Example-
Create abstract class and abstract methods


abstract class is created by ●
abstract class method has to be
deriving from the meta class decorated with @abstractmethod
ABC which belongs to the abc decorator.
(Abstract Base Class) ●
From abc module @abstractmethod
● module. Example Abstract decorator has to be imported to
from
class
abc import ABC use that annotation.
Class MyClass(ABC):

Example Abstrtact method
from abc import ABC, abstractmethod
Class MyClass(ABC):
@abstractmethod
def mymethod(self):
#empty body
pass
Astraction Example
from abc import ABC, abstractmethod class Child1(Parent):
class Parent(ABC): def vary(self):
print('In vary method of Child1')
#common functionality
def common(self): class Child2(Parent):
print('In common method of Parent') def vary(self):
@abstractmethod print('In vary method of Child2')
def vary(self):
# object of Child1 class
pass obj = Child1()
obj.common() #calls from parent
OUTPUT-
class
In common method of Parent
In vary method of Child1 obj.vary()
In common method of Parent # object of Child2 class
In vary method of Child2 obj = Child2()
obj.common() #calls from parent
class
obj.vary()
Polymorphism

Polymorphism is based on the greek words Poly (many) and
morphism (forms).

The word polymorphism means having many forms.

In programming, polymorphism means same function name
(but different signatures) being uses for different types.

Two ways top achieve polymorphism-

1. Method overloading- Same method name but different

parameter e.g. 10+5=15

“10”+”5”=105

2. Method Overriding-Same Method name and same parameters
Polymorphism Example
Example of Polymorphism
#polymorphism- method overriding objecta = Bird()
class Animals: objectd =
def Introduction(self): Dog() objectc=
print("There are many types of Animals.") Cat()

def makesound(self): objecta.introduction()


print("differrent animals having different objecta.maksound()
sounds")
objectd.introduction()
class Cat(Animals): objectd.maksound()
def maksound(self): #overrided
method print("Meow meow") objectc.introduction()
objectc.maksound()
class Dog(Bird):
def makesound(self): #overrided method
print("woof...woof/ Barking")

You might also like