Object Oriented Programming (OOP) : PPS UNIT-5
Object Oriented Programming (OOP) : PPS UNIT-5
Object Oriented Programming (OOP) : PPS UNIT-5
UNIT-5
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-
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
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
• 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.
• 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 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
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