Unit – 2 Basics of Object Oriented
Programming
By Pradipsinh Chavda
Topics to be covered
• POP vs OOP
• Oops Concepts
• Class and Object
• Constructor
• Types of Method
• Data Encapsulation
• Inheritance
• Polymorphism through inheritance/ Method Overriding
• Abstraction – Abstract class
POP vs OOP
• POP vs OOP
• POP, refers to Procedural Oriented Programming and its deals with
programs and functions. Programs are divided into functions and data is
global.
• OOP, refers to Object Oriented Programming and its deals with objects and
their properties. Major concepts of OOPs are −
•
OOP POP
Key
Definition OOP stands for Object Oriented POP stands for Procedural Oriented
1 Programing. Programming.
Approach OOP follows bottom up approach. POP follows top down approach.
2
Division A program is divided to objects and A program is divided into funtions and
3 their interactions. they interacts.
Inheritance Inheritance is supported. Inheritance is not supported.
supported
4
Access control Access control is supported via access No access modifiers are supported.
5 modifiers.
Data Hiding Encapsulation is used to hide data. No data hiding present. Data is globally
6 accessible.
Example Python, C++, Java C, Pascal
7
Oops Concepts
• Class
– A class is a template that specifies the
attributes and behavior of things or objects.
– A class is a blueprint or prototype from which
objects are created.
– Example: Employee, Student, Person, Shape
• Object
– An object is an instance of a class.
– An object means anything from real world like
as person, computer, bench etc
– Example: mark is Employee, Harsh is Student
•
• Inheritance
– Inheritance is the process, by which
class can acquire the properties and
methods of another class.
– The mechanism of deriving a new
class from an old class is called
inheritance.
– The new class is called derived
class and old class is called base class.
– The derived class may have all the
features of the base class.
Programmer can add new features
to the derived class
• Polymorphism
– A Greek word Polymorphism means
the ability to take more than one
form.
The concept of polymorphism is
characterized by the idea of ‘one
interface, multiple methods’,
• Encapsulation
– Wrapping up of a data and
functions into single unit is
known as encapsulation.
•
Abstraction
Just represent essential features without including the
background details.
It is used to implement in class to provide data security.
Class and Object
• Class:
– Class is a blueprint or code template for object creation.
– The class is a user-defined data structure that binds the data members and
methods into a single unit.
– Using a class, you can create as many objects as you want.
• Object:
– An object is an instance of a class. An object is a real-life entity.
– Objects have two characteristics:
• States – attributes/variable
• Behaviors - method
– Using its methods, we can modify its state.
• Example
• More Example?
Create a class and object
• In Python, class is defined by using the class keyword.
The syntax to create a class is given below.
Create Class Syntax:
class class_name:
<statement 1>
<statement 2>
..
<statement N>
Create Object Syntax:
<object-name> = <class-name>(<arguments>)
Example
Create a class named MyClass, with a property
named x:
class MyClass:
x=5
Create an object named p1, and print
the value of x:
p1 = MyClass()
print(p1.x)
Constructors
• The constructor is a method that is called when an object is
created. This method is defined in the class and can be used to
initialize basic variables.
• The constructor is created with the function init. As parameter we
write the self keyword, which refers to itself (the object).
Syntax:
def __init__(self, parameters..):
# initialization
Note: The self parameter is a reference to the current instance of the class, and
is used to access variables that belong to the class.
• The __init__() Function
– All classes have a function called __init__(), which is always
executed when the class is being initiated.
– Used to to assign values to object properties, or other
operations that are necessary to do when the object is being
created
• Note: The __init__() function is called automatically every
time the class is being used to create a new object.
•
Example:
class Person:
def __init__(self, name, sex, profession):
# data members (instance variables)
self.name = name
self.sex = sex
self.profession = profession
# Behavior (instance methods)
def show(self):
print('Name:', self.name, 'Sex:', self.sex, 'Profession:', self.profession)
# Behavior (instance methods)
def work(self):
print(self.name, 'working as a', self.profession)
• Create Object of a Class
Syntax:
<object-name> = <class-name>(<arguments>)
Example:
jessa = Person('Jessa', 'Female', 'Software Engineer')
class Person:
def __init__(self, name, sex, profession):
# data members (instance variables)
self.name = name
self.sex = sex
self.profession = profession
# Behavior (instance methods)
def show(self):
print('Name:', self.name, 'Sex:', self.sex, 'Profession:', self.profession)
# Behavior (instance methods) o/p
def work(self):
print(self.name, 'working as a', self.profession)
Name: Jessa Sex: Female Profession:
Software Engineer
# create object of a class Jessa working as a Software Engineer
jessa = Person('Jessa', 'Female', 'Software Engineer')
# call methods
jessa.show()
jessa.work()
Types of methods
• Instance method – method with self as first arg
• Class method
– Attribute/method is common to all Object
– Use @classmethod annotation on method
– A class method can be called either using the class or using an instance.
– Use cls as a parameter
• static method
– @staticmethod annotation
– Utility function
– No cls parameter required
– Independent to Object
class Student:
def __init__(self, a, b):
self.a = a
self.b = b
O/p
def avg(self): 15.0
return(self.a + self.b)/2
s1 = Student(10,20)
print(s1.avg())
class Student:
branch ='IT'
def __init__(self, name, age):
self.name = age
self.age = age
@classmethod O/P
def info(cls): IT
return cls.branch 20
print(Student.info()) IT
16
s=Student('het',20)
print(s.age)
print(s.info())
s1=Student('bhagya',16)
print(s1.age)
class Calculator:
# create addNumbers static method
@staticmethod
def addNumbers(x, y):
return x + y O/p
Product: 125
print('Product:', Calculator.addNumbers(15, 110))
Data Encapsulation
• Encapsulation in Python describes the concept of bundling
data and methods within a single unit.
• So, for example, when you create a class, it means you are
implementing encapsulation.
• Encapsulation can be achieved by declaring the data
members and methods of a class either as private or
protected.
• But In Python, we don’t have direct access modifiers like
public, private, and protected.
• We can achieve this by using single and double underscore
• Access modifiers limit access to the variables and
methods of a class. Python provides three types
of access modifiers private, public, and protected.
• Public Member: Accessible anywhere from
outside of class. By default
• Private Member(__): Accessible within the class
• Protected Member(_): Accessible within the class
and its sub-classes
class Employee:
# constructor
def __init__(self, name, salary):
# public data members
self.name = name Public member
self.salary = salary
# public instance methods
def show(self):
# accessing public data member
print("Name: ", self.name, 'Salary:', self.salary)
O/p
# creating object of a class Name: Jessa Salary: 10000
emp = Employee('Jessa', 10000)
Name: Jessa Salary: 10000
# accessing public data members
print("Name: ", emp.name, 'Salary:', emp.salary)
# calling public method of the class
emp.show()
class Employee:
# constructor
def __init__(self, name, salary):
Private Member
# public data member
self.name = name
# private member AttributeError: 'Employee' object has no
self.__salary = salary attribute '__salary'
# creating object of a class
emp = Employee('Jessa', 10000)
# accessing private data members
print('Salary:', emp.__salary)
class user:
def __init__(self, id, name):
self._id = id
self._name = name
Protected member
def _userdetails(self):
print("Id: {}, Name: {}".format(self._id, self._name))
class Employees(user): Output:
pass
1
e1 = Employees(1, "Suresh") Suresh
print(e1._id) Id: 1, Name: Suresh
print(e1._name)
e1._userdetails()
Inheritance
• Powerful concept of OOPs
• Using the inheritance concept, we can use the existing features of one class in another class.
• Inheritance provides code reusability to the program because we can use an existing class to create a new
class instead of creating it from scratch.
• The inheritance is the process of acquiring the properties of one class to another class.
• In inheritance, we use the terms like parent class, child class, base class, derived class, superclass, and
subclass.
• The Parent class is the class which provides features to another class. The parent class is also known as
Base class or Superclass.
• The Child class is the class which receives features from another class. The child class is also known as the
Derived Class or Subclass.
• There are five types of inheritances, and they are as follows.
– Single Inheritance
– Multiple Inheritance
– Multi-Level Inheritance
– Hierarchical Inheritance
– Hybrid Inheritance
Creating a Child Class
Syntax:
class derived-class(baseclass):
<class-suite>
A class can inherit multiple classes by mentioning all of them
inside the bracket.
Syntax:
class derive-class(<base class 1>, <base class 2>, ..... <base class n>):
<class - suite>
• Single Inheritance: one child class derives from one parent class
class Animal:
def speak(self):
print("Animal Speaking")
#child class Dog inherits the base class Animal
class Dog(Animal):
def bark(self):
print("dog barking")
d = Dog()
d.bark()
d.speak()
O/p:
dog barking Animal Speaking
• Multi-Level inheritance
• When a child class becomes a parent class for
another child class.
• There is no limit on the number of levels up to
which, the multi-level inheritance
.Syntax
class
. class1:
<class-suite>
class class2(class1):
<class suite>
class class3(class2):
<class suite>
class Animal:
def speak(self):
print("Animal Speaking") Multi-level Example
#The child class Dog inherits the base class Animal
class Dog(Animal):
def bark(self):
print("dog barking") O/p
#The child class Dogchild inherits another child class Dog dog barking
class DogChild(Dog):
def eat(self): Animal Speaking
print("Eating bread...") Eating bread...
d = DogChild()
d.bark()
d.speak()
d.eat()
• Multiple Inheritance
Syntax
– child class inherits from more class Base1:
<class-suite>
than one parent class.
class Base2:
<class-suite>
.
.
.
class BaseN:
<class-suite>
class Derived(Base1, Base2, ......
BaseN):
<class-suite>
class Calculation1:
def Summation(self,a,b):
return a+b
class Calculation2: Multiple Inheritance
def Multiplication(self,a,b):
return a*b
class Derived(Calculation1,Calculation2):
O/p:
30
def Divide(self,a,b):
200
return a/b
0.5
d = Derived()
print(d.Summation(10,20))
print(d.Multiplication(10,20))
print(d.Divide(10,20))
• Hierarchical Inheritance
– two or more child classes derive from one parent
class.
class Vehicle:
def info(self):
print("This is Vehicle")
class Car(Vehicle): Hierarchical Inheritance
def car_info(self, name):
print("Car name is:", name)
class Truck(Vehicle):
Output
def truck_info(self, name):
print("Truck name is:", name) This is Vehicle
Car name is: BMW
obj1 = Car()
obj1.info() This is Vehicle
obj1.car_info('BMW') Truck name is: Ford
obj2 = Truck()
obj2.info()
obj2.truck_info('Ford')
• Hybrid Inheritance
– When inheritance is consists of multiple types or a
combination of different inheritance is called
hybrid inheritance.
Polymorphism through inheritance
• Polymorphism refers to having multiple forms.
For example, inbuilt polymorphic function
len("hello") # returns 5 as result
len([1,2,3,4,45,345,23,42]) # returns 8 as result
In this case the function len is polymorphic as it is taking string as input in
the first case and is taking list as input in the second case.
• Method overriding is a type of polymorphism in
which a child class which is extending the parent
class can provide different definition to any
function defined in the parent class as per its own
requirements
• We can provide some specific implementation of
the parent class method in our child class. When
the parent class method is defined in the child
class with some specific implementation, then
the concept is called method overriding.
class Bank:
def getroi(self):
return 10
class SBI(Bank):
def getroi(self):
return 7
Output:
class ICICI(Bank):
def getroi(self):
return 8 Bank Rate of interest: 10
SBI Rate of interest: 7
b1 = Bank() ICICI Rate of interest: 8
b2 = SBI()
b3 = ICICI()
print("Bank Rate of interest:",b1.getroi());
print("SBI Rate of interest:",b2.getroi());
print("ICICI Rate of interest:",b3.getroi());
Abstraction - abstract class
• It is used to hide the background details or any
unnecessary implementation.
• User is familiar with that "what function does" but
they don't know "how it does.“
• In simple words, we all use the smartphone and very
much familiar with its functions such as camera, voice-
recorder, call-dialing, etc., but we don't know how
these operations are happening in the background.
• In Python, abstraction can be achieved by using abstract
classes and methods.
• Any class that contains abstract method(s) is called an
abstract class.
• Abstract methods do not include any implementations – they
are always defined and implemented as part of the methods
of the sub-classes inherited from the abstract class.
Syntax:
from abc import ABC
class ClassName(ABC):
pass
• To define an abstract method, you use the
@abstractmethod decorator:
from abc import ABC, abstractmethod
class AbstractClassName(ABC):
@abstractmethod
def abstract_method_name(self):
pass
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod Abstract Example
def area(self):
pass
class Rectangle(Shape):
def __init__(self, x,y):
self.l = x Output:
self.b = y area: 200
def area(self):
return self.l*self.b
r = Rectangle(10,20)
print ('area: ',r.area())
#s=Shape()
#TypeError: Can't instantiate abstract class Shape with abstract methods area
•Thank you