Nothing Special   »   [go: up one dir, main page]

Object Oriented Programming (OOP) : PPS UNIT-5

Download as pdf or txt
Download as pdf or txt
You are on page 1of 48

PPS

UNIT-5

Object Oriented Programming


(OOP)
--Er. P. N. Shingote
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.
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.
Example 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

FORTRAN and COBOL are two popular procedural
programming languages.
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.

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.
Object Oriented Programming
Features of OOP
1. Class- Logical ntity, 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
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)
OUTPUT-
s2=student("pqrs",25) 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,arg3......)

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-
Abcd got 30
Pqrs got 25
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 software')
intentionally.

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

Inheritance uses is-a type of relationship.

Syntax of inheritance in Python

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 1001


self.acctnum = acctnum

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-

A TV set where we enjoy programs with out knowing the inner
details of how TV works.
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) module. 
From abc module @abstractmethod

Example Abstract class decorator has to be imported to use
from abc import ABC 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 class
OUTPUT-
obj.vary()
In common method of Parent
In vary method of Child1
# object of Child2 class
In common method of Parent obj = Child2()
In vary method of 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 = Dog()
def Introduction(self): objectc= Cat()
print("There are many types of Animals.")
objecta.introduction()
def makesound(self): objecta.maksound()
print("differrent animals having different
sounds") objectd.introduction()
objectd.maksound()
class Cat(Animals):
def maksound(self): #overrided method objectc.introduction()
print("Meow meow") objectc.maksound()

class Dog(Bird):
def makesound(self): #overrided method
print("woof...woof/ Barking")
Assignment on Unit 5
OOP

You might also like