Unit V Python OOPs Concepts
Unit V Python OOPs Concepts
Unit V
Object Oriented Programming In Python
h
ik
5a. Creating Classes and Objects to solve the given problem
ha
5b Write Python code for data hiding for the given problem
.S
5c. Write Python code using data abstraction for the given problem
5d. Write Python program using inheritance for the for the given problem
.A
.A
of
Pr
1
Padmashri Dr. Vitthalrao Vikhe Patil Institute Of Technology & Engineering (Polytechnic ), Pravaranagar
PWP-22616,CM
Object
h
The object is an entity that has state and behavior. It may be any real-world object like
the mouse, keyboard, chair, table, pen, etc.
ik
Everything in Python is an object, and almost everything has attributes and methods. All
ha
functions have a built-in attribute __doc__, which returns the doc string defined in the
function source code.
Class
.S
The class can be defined as a collection of objects. It is a logical entity that has some
specific attributes and methods. For example: if you have an Student class then it should
contain an attribute and method, i.e. an email id, name, age, salary, etc.
.A
Syntax
class ClassName:
.A
<statement-1>
.
.
of
<statement-N>
Pr
Method
The method is a function that is associated with an object. In Python, a method is not
unique to class instances. Any object type can have methods.
Inheritance
Inheritance is the most important aspect of object-oriented programming which simulates
the real world concept of inheritance. It specifies that the child object acquires all the
properties and behaviors of the parent object.
By using inheritance, we can create a class which uses all the properties and behavior of
another class. The new class is known as a derived class or child class, and the one whose
properties are acquired is known as a base class or parent class.
It provides re-usability of the code.
Polymorphism
Polymorphism contains two words "poly" and "morphs". Poly means many and Morphs
means form, shape.
By polymorphism, we understand that one task can be performed in different ways.
2
Padmashri Dr. Vitthalrao Vikhe Patil Institute Of Technology & Engineering (Polytechnic ), Pravaranagar
PWP-22616,CM
For example You have a class animal, and all animals speak. But they speak differently.
Here, the "speak" behavior is polymorphic in the sense and depends on the animal. So,
the abstract "animal" concept does not actually "speak", but specific animals (like dogs
and cats) have a concrete implementation of the action "speak".
Encapsulation
Encapsulation is also an important aspect of object-oriented programming.
It is used to restrict access to methods and variables.
In encapsulation, code and data are wrapped together within a single unit from being
modified by accident.
Data Abstraction
Data abstraction and encapsulation both are often used as synonyms. Both are nearly
synonym because data abstraction is achieved through encapsulation.
Abstraction is used to hide internal details and show only functionalities.
Abstracting something means to give names to things so that the name captures the core
of what a function or a whole program does.
h
Object-oriented vs Procedure-oriented Programming languages
ik
Object-oriented Programming Procedural Programming
Object-oriented programming is the Procedural programming uses a list of
ha
problem-solving approach and used instructions to do computation step by
where computation is done by using step.
.S
objects.
It makes the development and In procedural programming, It is not
.A
It simulates the real world entity. So real- It doesn't simulate the real world. It
world problems can be easily solved works on step by step instructions
through oops. divided into small parts called
of
functions.
Pr
3
Padmashri Dr. Vitthalrao Vikhe Patil Institute Of Technology & Engineering (Polytechnic ), Pravaranagar
PWP-22616,CM
h
class ClassName:
ik
#statement_suite
In python, we must notice that each class is associated with a documentation string which
ha
can be accessed by using <class-name>.__doc__.
A class contains a statement suite including fields, constructor, function, etc. definition.
.S
Consider the following example to create a class Student which contains two fields as
Student rollno, and name.
The class also contains a function display() which is used to display the information of
.A
the Student.
Example
class Student:
.A
id = 10;
name = "asharf"
of
Here, the self is used as a reference variable which refers to the current class object. It is
always the first argument in the function definition. However, using self is optional in the
function call.
4
Padmashri Dr. Vitthalrao Vikhe Patil Institute Of Technology & Engineering (Polytechnic ), Pravaranagar
PWP-22616,CM
class Student:
id = 10;
name = "Asharf"
def display (self):
print("ID: %d \nName: %s"%(self.id,self.name))
stud = Student()
stud.display()
Output:
ID: 10
Name: Asharf
Python Constructor
A constructor is a special type of method (function) which is used to initialize the
h
instance members of the class.
ik
Constructors can be of two types.
1. Parameterized Constructor
2. Non-parameterized Constructor
ha
Constructor definition is executed when we create the object of this class. Constructors
.S
also verify that there are enough resources for the object to perform any start-up task.
.A
We can pass any number of arguments at the time of creating the class object, depending
upon __init__ definition.
It is mostly used to initialize the class attributes. Every class must have a constructor,
of
class Student:
def __init__(self,name,id):
self.id = id;
self.name = name;
def display (self):
print("ID: %d \nName: %s"%(self.id,self.name))
stud1 = Student("Asharf",101)
stud 2 = Student("Sachin",102)
#accessing display() method to print Student information
emp1.display();
#accessing display() method to print Student 2 information
emp2.display();
5
Padmashri Dr. Vitthalrao Vikhe Patil Institute Of Technology & Engineering (Polytechnic ), Pravaranagar
PWP-22616,CM
Output:
ID: 101
Name: Asharf
ID: 102
Name: Sachin
Example: Counting the number of objects of a class
class Student:
count = 0
def __init__(self):
Student.count = Student.count + 1
s1=Student()
s2=Student()
s3=Student()
h
print("The number of students:",Student.count)
ik
Output:
ha
The number of students: 3
Python Non-Parameterized Constructor Example
class Student:
.S
# Constructor - non parameterized
def __init__(self):
.A
student = Student()
student.show("Asharf")
of
Output:
This is non parametrized constructor
Pr
Hello Asharf
Python Parameterized Constructor 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("Asharf")
student.show()
6
Padmashri Dr. Vitthalrao Vikhe Patil Institute Of Technology & Engineering (Polytechnic ), Pravaranagar
PWP-22616,CM
Output:
This is parametrized constructor
Hello Asharf
Python In-built class functions
The in-built functions defined in the class are described in the following table.
Sr. No. Function Description
1 getattr(obj,name,default) It is used to access the attribute of
the object.
2 setattr(obj, name,value) It is used to set a particular value to
the specific attribute of an object
.
3 delattr(obj, name) It is used to delete a specific
attribute.
4 hasattr(obj, name) It returns true if the object contains
some specific attribute.
h
Example
ik
class Student:
def __init__(self,name,id,age):
self.name = name;
self.id = id; ha
.S
self.age = age
.A
setattr(s,"age",23)
print(hasattr(s,'id'))
# deletes the attribute age
delattr(s,'age')
# this will give an error since the attribute age has been deleted
print(s.age)
7
Padmashri Dr. Vitthalrao Vikhe Patil Institute Of Technology & Engineering (Polytechnic ), Pravaranagar
PWP-22616,CM
Output:
Asharf
23
True
AttributeError: 'Student' object has no attribute 'age'
Built-in class attributes
Along with the other attributes, a python class also contains some built-in class attributes
which provide information about the class.
The built-in class attributes are given in the below table.
Sr. No. Attribute Description
1 __dict__ It provides the dictionary containing the
information about the class namespace.
2 __doc__ It contains a string which has the class
documentation
3 __name__ It is used to access the class name.
h
4 __module__ It is used to access the module in which,
ik
this class is defined.
ha
5 __bases__ It contains a tuple including all base
classes.
Example
.S
class Student:
def __init__(self,name,id,age):
.A
self.name = name;
self.id = id;
self.age = age
.A
def display_details(self):
print("Name:%s, ID:%d, age:%d"%(self.name,self.id))
of
s = Student("John",101,22)
print(s.__doc__)
Pr
print(s.__dict__)
print(s.__module__)
Output:
None
{'name': 'John', 'id': 101, 'age': 22}
__main__
8
Padmashri Dr. Vitthalrao Vikhe Patil Institute Of Technology & Engineering (Polytechnic ), Pravaranagar
PWP-22616,CM
Python Inheritance
Inheritance is an important aspect of the object-oriented paradigm.
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.
In inheritance, the child class acquires the properties and can access all the data
members and functions defined in the parent class.
A child class can also provide its specific implementation to the functions of the
parent class..
In python, a derived class can inherit base class by just mentioning the base in the
bracket after the derived class name.
Syntax
class derived-class(base class):
<class-suite>
h
A class can inherit multiple classes by mentioning all of them inside the bracket.
ik
Consider the following syntax.
ha
Syntax
class derive-class(<base class 1>, <base class 2>, ..... <base class n>):
.S
<class - suite>
Example 1
class Animal:
.A
def speak(self):
print("Animal Speaking")
.A
def bark(self):
print("dog barking")
Pr
d = Dog()
d.bark()
d.speak()
Output:
dog barking
Animal Speaking
9
Padmashri Dr. Vitthalrao Vikhe Patil Institute Of Technology & Engineering (Polytechnic ), Pravaranagar
PWP-22616,CM
h
The syntax of multi-level inheritance is given below.
ik
Syntax
class class1:
ha
<class-suite>
class class2(class1):
.S
<class suite>
class class3(class2):
.A
<class suite>
.
.
.A
Example
class Animal:
of
def speak(self):
print("Animal Speaking")
Pr
10
Padmashri Dr. Vitthalrao Vikhe Patil Institute Of Technology & Engineering (Polytechnic ), Pravaranagar
PWP-22616,CM
Output:
dog barking
Animal Speaking
Eating bread...
h
ik
The syntax to perform multiple inheritance is given below.
ha
Syntax
class Base1:
.S
<class-suite>
class Base2:
.A
<class-suite>
.
.A
.
.
class BaseN:
of
<class-suite>
Pr
print(d.Summation(10,20))
print(d.Multiplication(10,20))
print(d.Divide(10,20))
Output:
30
200
0.5
h
Example
ik
class Calculation1:
def Summation(self,a,b):
return a+b;
class Calculation2:
ha
.S
def Multiplication(self,a,b):
return a*b;
.A
class Derived(Calculation1,Calculation2):
def Divide(self,a,b):
return a/b;
.A
d = Derived()
print(issubclass(Derived,Calculation2))
of
print(issubclass(Calculation1,Calculation2))
Output:
Pr
True
False
12
Padmashri Dr. Vitthalrao Vikhe Patil Institute Of Technology & Engineering (Polytechnic ), Pravaranagar
PWP-22616,CM
return a*b;
class Derived(Calculation1,Calculation2):
def Divide(self,a,b):
return a/b;
d = Derived()
print(isinstance(d,Derived))
Output:
True
Method Overriding
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. We may need to
h
perform method overriding in the scenario where the different definition of a parent
ik
class method is needed in the child class.
Consider the following example to perform method overriding in python.
class Animal:
def speak(self): ha
.S
print("speaking")
class Dog(Animal):
.A
def speak(self):
print("Barking")
d = Dog()
.A
d.speak()
Output:
of
Barking
Real Life Example of method overriding
Pr
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()
13
Padmashri Dr. Vitthalrao Vikhe Patil Institute Of Technology & Engineering (Polytechnic ), Pravaranagar
PWP-22616,CM
h
Consider the following example.
ik
class Employee:
__count = 0;
def __init__(self):
Employee.__count = Employee.__count+1
ha
.S
def display(self):
print("The number of employees",Employee.__count)
.A
emp = Employee()
emp2 = Employee()
try:
.A
print(emp.__count)
finally:
of
emp.display()
Output:
Pr
14