Complete Unit 5 OOP Notes SPPU
Complete Unit 5 OOP Notes SPPU
Complete Unit 5 OOP Notes SPPU
By-
Ms. Swati M. Suryawanshi
Introduction
Program- program is collection of instructions that tells the
computer how to solve a particular problem.
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 .
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
⚫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.
• 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.
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
•
The _ _init_ _() method/class constructor
• The init () method is automatically executed when an object of a class
is created.
•
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.
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
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.
@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
• 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
● 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(_ _).
If for some reason you can access private variables outside the class
• using object name and class name.
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
●
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)
●
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()