What is Object Oriented Programming
Object oriented Programming is a new programming technique that allows
the analysis and design of an application in terms of entities or an object.
Object Oriented programming is a programming style that is associated with
the concept of Class, Objects and various other concepts revolving around
these two, like Inheritance, Polymorphism, Abstraction, Encapsulation etc
The main aim of OOP is to bind together the data and the functions that
operate on them so that no other part of the code can access this data
except that function.
Class
Class is a keyword which is used to describe a particular entity set their
attributes and their behavior.
Object
An Object is a real world entity.
or
An object is the instance of the class that takes the space in the memory.
Each instance of the class has its own value for each attribute but shares the
attribute name and behaviour.
Difference between class and an object
Class is used to describe group of similar entities called entity set
whereas an object represent single entity
Class does not take any space in the memory whereas an object of the
class takes the space in the memory
Class is a static entity whereas an object is dynamic entity
Why Object Oriented Programming
1. Simplicity
The complexity is reduced because the program structure is very clear;
2. Easy to Modify
The programes written with OOP are really easy to understand. It is
always easy and time-saving to modify the existing codes with
incorporating new changes into it.
3. Method overloading
Overloading is possible in object oriented programming.
4. Reusability
OOP approach offers the reusability of classes. We can reuse the classes
that are already created without writing them again and again
5. parallel development
Since the parallel development of classes is possible in OOP concept, It
results in the quick development of the complete programmes
6. Secure
It is a secured development technique since data is hidden and can’t be
accessed by external functions.
7. Data Redundancy
the data redundancy is one of the greatest advantages of OOP. If a user
wants a similar functionality in multiple classes he/she can go ahead by
writing common class definitions for the similar functionalities and inherit
them.
8. Faster development
Reuse enables faster development. Object-oriented programming
languages come with rich libraries of objects,and code developed during
projects is also reusable in future projects.
9. Lower cost development
The reuse of software also lowers the cost of development. Typically,
more effort is put into the object-oriented analysis and design, which
lowers the overall cost of development.
Main features of object oriented programming Language
The 4 main features of Object Oriented programming are:
Encapsulation
Abstraction
Inheritance
Polymorphism
Encapsulation
Encapsulation is grouping of properties and methods within a class
Abstraction
Abstraction is one of the most essential and important feature of object
oriented programming in Python. Abstraction means displaying only
essential information and hiding the details.
Consider a real life example of a man driving a car. The man only knows that
pressing the accelerators will increase the speed of car or applying brakes
will stop the car but he does not know about how on pressing accelerator the
speed is actually increasing, he does not know about the inner mechanism of
the car or the implementation of accelerator, brakes etc in the car. This is
what abstraction is.
Abstraction using Classes: We can implement Abstraction in Python using
classes. Class helps us to group data members and member functions using
available access specifiers. A Class can decide which data member will be
visible to outside world and which is not.
Abstraction in Header files: One more type of abstraction in Python can
be header files. For example, consider the pow() method present in math.h
header file. Whenever we need to calculate power of a number, we simply
call the function pow() present in the math.h header file and pass the
numbers as arguments without knowing the underlying algorithm according
to which the function is actually calculating power of numbers
Inheritance
Inheritance is a mechanism that enable one class to inherit all the behavior
and attributes of another class.
Important terminology:
Super Class: The class whose features are inherited is known as
superclass(or a base class or a parent class).
Sub Class: The class that inherits the other class is known as subclass(or a
derived class, extended class, or child class). The subclass can add its own
fields and methods in addition to the superclass fields and methods.
Reusability: Inheritance supports the concept of “reusability”, i.e. when we
want to create a new class and there is already a class that includes some of
the code that we want, we can derive our new class from the existing class.
By doing this, we are reusing the fields and methods of the existing class.
Single inheritance: When a child class inherits from only one parent class,
it is called as single inheritance.
Multi-level inheritance :is archived when a derived class inherits another
derived class. There is no limit on the number of levels up to which, the
multi-level inheritance is archived in python.
hierarchical inheritance:When more than one derived classes are created
from a single base – it is called hierarchical inheritance.
Multiple Inherit: Python provides us the flexibility to inherit multiple base
classes in the child class.
Polymorphism
Polymorphism means that the same function may behave differently on the
different classes
How to Create class and an Object
class Employee:
id = 10
name = "Devansh"
def display (self):
print(self.id,self.name)
The self-parameter
The self-parameter refers to the current instance of the class and
accesses the class variables.
Creating an instance of the class
A class needs to be instantiated if we want to use the class attributes in
another class or method. A class can be instantiated by calling the class
using the class name.
class Employee:
id = 10
name = "John"
def display (self):
print("ID: %d \nName: %s"%(self.id,self.name))
# Creating a emp instance of Employee class
emp = Employee()
emp.display()
What is Constructor
Constructor is a special method that has the same name as that of your
class. Constructor can take the parameters but it can not return any
value. Constructor is automatically called when the object of the class is
created. Constructors are used to initialize the members of the class. If
there is no any constructor in your class then compiler automatically
creates zero argument constructor for your class.
In Python, the method the __init__() simulates the constructor of the class. This method is
called when the class is instantiated. It accepts the self-keyword as a first argument which
allows accessing the attributes or method of the class.
Python Non-Parameterized Constructor
Example
class Student:
# Constructor - non parameterized
def __init__(self):
print("This is non parametrized constructor")
def show(self,name):
print("Hello",name)
student = Student()
student.show("John")
Python Parameterized Constructor
The parameterized constructor has multiple parameters along with the self. Consider the
following example.
Example
class Student:
# Constructor - parameterized
def __init__(self, name):
print("This is parametrized constructor")
self.name = name
def show(self):
print("Hello",self.name)
student = Student("John")
student.show()
Another Example
class car:
def __init__(self,modelname, year):
self.modelname = modelname
self.year = year
def display(self):
print(self.modelname,self.year)
c1 = car("Toyota", 2016)
c1.display()
Method overloading
Overloaded methods are those methods that are in same class and have same name but
different parameter list.
Like other languages (for example method overloading in C++) do, python does not
supports method overloading. We may overload the methods but can only use the latest
defined method.
def area(a, b):
p=a*b
print(p)
def area(a, b, c):
p = a * b*c
print(p)
area(4, 5, 5)
area(4,8)
In Python you can define a method in such a way that there are multiple ways to call it.
Depending on the function definition, it can be called with zero, one, two or more
parameters. This is known as method overloading.
In the given code, there is a class with one method sayHello(). We rewrite as shown below.
The first parameter of this method is set to None, this gives us the option to call it with or
without a parameter.
An object is created based on the class, and we call its method using zero and one
parameter. To implement method overloading, we call the method sayHello() in two ways:
1. obj.sayHello() and 2.obj.sayHello('Rambo')
class Human:
def sayHello(self, name=None):
if name is not None:
print 'Hello ' + name
else:
print 'Hello '
obj = Human()
print(obj.sayHello())
print(obj.sayHello('Rambo'))
Python Inheritance
In python, a derived class can inherit base class by just mentioning the base in the bracket after
the derived class name.
Syntax
1. class derived-class(base class):
2. <class-suite>
A class can inherit multiple classes by mentioning all of them inside the bracket. Consider the
following syntax.
Syntax
class derive-class(<base class 1>, <base class 2>, ..... <base class n>):
<class - suite>
Example 1
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()
Output:
dog barking
Animal Speaking
Python Multi-Level inheritance
Example
class Animal:
def speak(self):
print("Animal Speaking")
#The child class Dog inherits the base class Animal
class Dog(Animal):
def bark(self):
print("dog barking")
#The child class Dogchild inherits another child class Dog
class DogChild(Dog):
def eat(self):
print("Eating bread...")
d = DogChild()
d.bark()
d.speak()
d.eat()
Python Multiple inheritance
Example
class Calculation1:
def Summation(self,a,b):
return a+b;
class Calculation2:
def Multiplication(self,a,b):
return a*b;
class Derived(Calculation1,Calculation2):
def Divide(self,a,b):
return a/b;
d = Derived()
print(d.Summation(10,20))
print(d.Multiplication(10,20))
print(d.Divide(10,20))
Output:
30
200
0.5
What is Method Overriding
Overridden methods are those methods that are in super class as well as in sub class. Method
Overriding is used when we want to redefine the method of super class in the sub class.
Consider the following example to perform method overriding in python.
class Animal:
def speak(self):
print("speaking")
class Dog(Animal):
def speak(self):
print("Barking")
d=Dog()
d.speak()
Real Life Example of method overriding
class Bank:
def getroi(self):
return 10;
class SBI(Bank):
def getroi(self):
return 7;
class ICICI(Bank):
def getroi(self):
return 8;
b1=Bank()
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());
Deleting Object Property
We can delete the properties of the object or object itself by using the del keyword.
Consider the following example.
Example
class Employee:
def __init__(self):
self.id = 10
self.name = "John"
def display(self):
print(self.id,self.name)
emp = Employee()
del emp.id # Now it works
emp.display()
Deleting object
class Employee:
id = 10
name = "John"
def display(self):
print("ID: %d \nName: %s" % (self.id, self.name))
# Creating a emp instance of Employee class
emp = Employee()
# Deleting the property of object
# Deleting the object itself
del emp
emp.display()
Access Modifiers in Python : Public, Private and
Protected
Public Access Modifier
Protected Access Modifier
Private Access Modifier
Public Access Modifier:
The members of a class that are declared public are easily accessible from any part of
the program. All data members and member functions of a class are public by default.
# program to illustrate public access modifier in a class
classGeek:
# constructor
def__init__(self, name, age):
# public data mambers
self.geekName =name
self.geekAge =age
# public memeber function
defdisplayAge(self):
# accessing public data member
print("Age: ", self.geekAge)
# creating object of the class
obj =Geek("R2J", 20)
# accessing public data member
print("Name: ", obj.geekName)
# calling public member function of the class
obj.displayAge()
Output:
Name: R2J
Age: 20
In the above program, geekName and geekAge are public data members
and displayAge() method is a public member function of the class Geek. These data
members of the class Geek can be accessed from anywhere in the program.
Protected Access Modifier:
The members of a class that are declared protected are only accessible to a class
derived from it. Data members of a class are declared protected by adding a single
underscore ‘_’ symbol before the data member of that class.
# program to illustrate protected access modifier in a class
# super class
classStudent:
# protected data members
_name =None
_roll =None
_branch =None
# constructor
def__init__(self, name, roll, branch):
self._name =name
self._roll =roll
self._branch =branch
# protected member function
def_displayRollAndBranch(self):
# accessing protected data members
print("Roll: ", self._roll)
print("Branch: ", self._branch)
# derived class
classGeek(Student):
# constructor
def__init__(self, name, roll, branch):
Student.__init__(self, name, roll, branch)
# public member function
defdisplayDetails(self):
# accessing protected data members of super class
print("Name: ", self._name)
# accessing protected member functions of super class
self._displayRollAndBranch()
# creating objects of the derived class
obj =Geek("R2J", 1706256, "Information Technology")
# calling public member functions of the class
obj.displayDetails()
Output:
Name: R2J
Roll: 1706256
Branch: Information Technology
In the above program, _name, _roll and _branch are protected data members
and _displayRollAndBranch() method is a protected method of the super class Student.
The displayDetails() method is a public member function of the class Geek which is derived
from the Student class, the displayDetails() method in Geek class accesses the protected data
members of the Student class.
Private Access Modifier:
The members of a class that are declared private are accessible within the class only,
private access modifier is the most secure access modifier. Data members of a class
are declared private by adding a double underscore ‘__’ symbol before the data
member of that class.
# program to illustrate private access modifier in a class
classGeek:
# private members
__name =None
__roll =None
__branch =None
# constructor
def__init__(self, name, roll, branch):
self.__name =name
self.__roll =roll
self.__branch =branch
# private member function
def__displayDetails(self):
# accessing private data members
print("Name: ", self.__name)
print("Roll: ", self.__roll)
print("Branch: ", self.__branch)
# public member function
defaccessPrivateFunction(self):
# accesing private member function
self.__displayDetails()
# creating object
obj =Geek("R2J", 1706256, "Information Technology")
# calling public member function of the class
obj.accessPrivateFunction()
Output:
Name: R2J
Roll: 1706256
Branch: Information Technology
In the above program, _name, _roll and _branch are private members, __displayDetails() method
is a private member function (these can only be accessed within the class)
and accessPrivateFunction() method is a public member function of the class Geek which can
be accessed from anywhere within the program. The accessPrivateFunction() method
accesses the private members of the class Geek.
Data Hiding
class Person:
def __init__(self):
self.__age = 0 # Private instance variable
# Getter method
def get_age(self):
return self.__age
# Setter method with validation
def set_age(self, age):
if age < 0:
print("Age cannot be negative!")
else:
self.__age = age
# Create an object
p = Person()
# Try to set age using setter method
p.set_age(25)
# Get age using getter method
print("Age:", p.get_age())
# Try to set invalid age
p.set_age(-5)