5 Object Oriented Programming in Python
5 Object Oriented Programming in Python
Unit V
Object Oriented Programming In Python
1
Padmashri Dr. Vitthalrao Vikhe Patil Institute Of Technology & Engineering (Polytechnic ), Pravaranagar
PWP-22616,BD
Object
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.
Everything in Python is an object, and almost everything has attributes and methods. All
functions have a built-in attribute __doc__, which returns the doc string defined in the
function source code.
Class
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.
Syntax
class ClassName:
<statement-1>
.
.
<statement-N>
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,BD
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.
Object-oriented vs Procedure-oriented Programming languages
Object-oriented Programming Procedural Programming
Object-oriented programming is the Procedural programming uses a list of
problem-solving approach and used instructions to do computation step by
where computation is done by using step.
objects.
It makes the development and In procedural programming, It is not
maintenance easier. easy to maintain the codes when the
project becomes lengthy.
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
functions.
It provides data hiding. So it is more Procedural language doesn't provide
secure than procedural languages. You any proper way for data binding, so it is
cannot access private data from less secure.
anywhere.
Example of object-oriented programming Example of procedural languages are:
languages is C++, Java, .Net, Python, C, Fortran, Pascal, VB etc.
C#, etc.
3
Padmashri Dr. Vitthalrao Vikhe Patil Institute Of Technology & Engineering (Polytechnic ), Pravaranagar
PWP-22616,BD
4
Padmashri Dr. Vitthalrao Vikhe Patil Institute Of Technology & Engineering (Polytechnic ), Pravaranagar
PWP-22616,BD
class Student:
id = 10;
name = "Rakesh"
def display (self):
print("ID: %d \nName: %s"%(self.id,self.name))
stud = Student()
stud.display()
Output:
ID: 10
Name: Rakesh
Python Constructor
A constructor is a special type of method (function) which is used to initialize the
instance members of the class.
Constructors can be of two types.
1. Parameterized Constructor
2. Non-parameterized Constructor
Constructor definition is executed when we create the object of this class. Constructors
also verify that there are enough resources for the object to perform any start-up task.
5
Padmashri Dr. Vitthalrao Vikhe Patil Institute Of Technology & Engineering (Polytechnic ), Pravaranagar
PWP-22616,BD
Output:
ID: 101
Name: Rakesh
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()
print("The number of students:",Student.count)
Output:
The number of students: 3
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("Rakesh")
Output:
This is non parametrized constructor
Hello Rakesh
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("Rakesh")
student.show()
6
Padmashri Dr. Vitthalrao Vikhe Patil Institute Of Technology & Engineering (Polytechnic ), Pravaranagar
PWP-22616,BD
Output:
This is parametrized constructor
Hello Rakesh
Destructor:
A class can define a special method called destructor with the help of _ _del_ _().
It is invoked automatically when the instance (object) is about to be destroyed.
It is mostly used to clean up non memory resources used by an instance(object).
Example: For Destructor
class student:
def __init__(self):
print("This is non parameterized constructor")
def __del__(self):
print("Destructor called")
s1=student()
s2=student()
del s1
Output:
This is non parameterized constructor
This is non parameterized constructor
Destructor called
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.
Example
class Student:
def __init__(self,name,id,age):
self.name = name;
self.id = id;
self.age = age
7
Padmashri Dr. Vitthalrao Vikhe Patil Institute Of Technology & Engineering (Polytechnic ), Pravaranagar
PWP-22616,BD
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)
Output:
Rakesh
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.
4 __module__ It is used to access the module in which,
this class is defined.
5 __bases__ It contains a tuple including all base
classes.
Example
class Student:
def __init__(self,name,id,age):
self.name = name;
self.id = id;
self.age = age
def display_details(self):
print("Name:%s, ID:%d, age:%d"%(self.name,self.id))
8
Padmashri Dr. Vitthalrao Vikhe Patil Institute Of Technology & Engineering (Polytechnic ), Pravaranagar
PWP-22616,BD
s = Student("John",101,22)
print(s.__doc__)
print(s.__dict__)
print(s.__module__)
Output:
None
{'name': 'John', 'id': 101, 'age': 22}
__main__
Method Overloading:
• Method overloading is the ability to define the method with the same name
but with a different number of arguments and data types.
• With this ability one method can perform different tasks, depending on the number of
arguments or the types of the arguments given.
• Method overloading is a concept in which a method in a class performs operations according to
the parameters passed to it.
• As in other language we can write a program having two methods with same name but with
different number of arguments or order of arguments but in python if we will try to do the same
we get the following issue with method overloading in python.
Example-
# To calculate area of rectangle
def area(length,breadth):
calc=length*breadth
print(calc)
# To calculate area of square
def area(size):
calc=size*size
print(calc)
area(3)
area(4,5)
Output-
9
Traceback (most recent call last):
File "D:\python programs\trial.py", line 10, in <module>
area(4,5)
TypeError: area() takes 1 positional argument but 2 were given
• Python does not support method overloading i.e it is not possible to define more than one
method with the same name in a class in python.
• This is because method arguments in python do not have a type. A method accepting one
argument can be called with an integer value, a string or a double as shown in example.
Example
Class demo:
def print_r(self,a,b):
print(a)
print(b)
obj=demo()
9
Padmashri Dr. Vitthalrao Vikhe Patil Institute Of Technology & Engineering (Polytechnic ), Pravaranagar
PWP-22616,BD
obj.print_r(10,'S')
obj.print_r('S',10)
Output:
10
S
S
10
• In the above example same method works for two different data types.
• It is clear that method overloading is not supported in python but that does not mean that we
cannot call a method with different number of arguments. There are couple of alternatives
available in python that make it possible to call the same method but with different number of
arguments.
10
Padmashri Dr. Vitthalrao Vikhe Patil Institute Of Technology & Engineering (Polytechnic ), Pravaranagar
PWP-22616,BD
Syntax:
Class A:
# Properties of class A
Class B(A):
# Class B inheriting property of class A
# more properties of class B
Example 1: Example of Inheritance without using constructor
class vehicle: #parent class
name="Maruti"
def display(self):
print("Name= ",self.name)
11
Padmashri Dr. Vitthalrao Vikhe Patil Institute Of Technology & Engineering (Polytechnic ), Pravaranagar
PWP-22616,BD
Multilevel Inheritance:
In multilevel inheritance, features of the base class and the derived class are further inherited into
the new derived class. This is similar to a relationship representing a child and grandfather.
12
Padmashri Dr. Vitthalrao Vikhe Patil Institute Of Technology & Engineering (Polytechnic ), Pravaranagar
PWP-22616,BD
Syntax:
Class A:
# Properties of class A
Class B(A):
# Class B inheriting property of class A
# more properties of class B
Class C(B):
# Class C inheriting property of class B
# thus, Class C also inherits properties of class A
# more properties of class C
13
Padmashri Dr. Vitthalrao Vikhe Patil Institute Of Technology & Engineering (Polytechnic ), Pravaranagar
PWP-22616,BD
Multiple Inheritance:
When a class can be derived from more than one base classes this type of inheritance is called
multiple inheritance. In multiple inheritances, all the features of the base classes are inherited
into the derived class.
Syntax:
Class A:
# variable of class A
# functions of class A
Class B:
14
Padmashri Dr. Vitthalrao Vikhe Patil Institute Of Technology & Engineering (Polytechnic ), Pravaranagar
PWP-22616,BD
# variable of class B
# functions of class B
Class C(A,B):
# Class C inheriting property of both class A and B
# more properties of class C
Example: Python program to demonstrate multiple inheritances
# Base class1
class Father:
def display1(self):
print("Father")
# Base class2
class Mother:
def display2(self):
print("Mother")
# Derived class
class Son(Father,Mother):
def display3(self):
print("Son")
s1 = Son()
s1.display3()
s1.display2()
s1.display1()
Output:
Son
Mother
Father
Hierarchical Inheritance:
When more than one derived classes are created from a single base this type of inheritance is
called hierarchical inheritance. In this program, we have a parent (base) class and two child
(derived) classes.
15
Padmashri Dr. Vitthalrao Vikhe Patil Institute Of Technology & Engineering (Polytechnic ), Pravaranagar
PWP-22616,BD
16
Padmashri Dr. Vitthalrao Vikhe Patil Institute Of Technology & Engineering (Polytechnic ), Pravaranagar
PWP-22616,BD
Output:
True
False
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
perform method overriding in the scenario where the different definition of a parent
class method is needed in the child 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()
Output:
Barking
17
Padmashri Dr. Vitthalrao Vikhe Patil Institute Of Technology & Engineering (Polytechnic ), Pravaranagar
PWP-22616,BD
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());
Output:
Bank Rate of interest: 10
SBI Rate of interest: 7
ICICI Rate of interest: 8
18
Padmashri Dr. Vitthalrao Vikhe Patil Institute Of Technology & Engineering (Polytechnic ), Pravaranagar
PWP-22616,BD
Output:
The number of employees 2
Attribute Error: 'Employee' object has no attribute '__count'
Method Overriding:
Method overriding is an ability of a class to change the implementation of a method provided
by one of its base class. Method overriding is thus a strict part of inheritance mechanism.
To override a method in base class, we must define a new method with same name and same
parameters in the derived class.
Overriding is a very important part of OOP since it is feature that makes inheritance exploit its
full power. Through method overriding a class may “copy” another class, avoiding duplicated
code and at the same time enhance or customize part of it.
Example: For method overriding
class A:
def display(self):
print("This is base class")
class B(A):
def display(self):
print("This is derived class")
obj=B() # instance of child
obj.display() # child class overriden method
Output-
This is derived class
Using super() Method:
The super() method gives you access to methods in a super class from the
subclass that inherits from it.
The super() method returns a temporary object of the superclass that then
allows you to call that superclass’s method.
Example: For method overriding with super()
class A:
def display(self):
print("This is base class")
class B(A):
def display(self):
super().display()
print("This is derived class")
obj=B() # instance of child
obj.display() # child class overriden method
Output-
This is base class
This is derived class
Composition Classes:
• In composition we do not inherit from the base class but establish
relationship between classes through the use of instance variables that are
references to other objects.
• Composition means that an object knows another object and explicitly
delegates some tasks to it. While inheritance is implicit, composition is
19
Padmashri Dr. Vitthalrao Vikhe Patil Institute Of Technology & Engineering (Polytechnic ), Pravaranagar
PWP-22616,BD
explicit in python.
• We use composition when we want to use some aspects of another class
without promising all of the features of that other class.
Syntax:
Class GenericClass:
Define some attributes and methods
Class AspecificClass:
Instance_variable_of_generic_class=GenericClass
#use this instance somewhere in the class
Some_method(instance_varable_of_generic_class)
• For example, we have three classes email, gmail and yahoo. In email class
we are referring the gmail and using the concept of composition.
Example:
class gmail:
def send_email(self,msg):
print("sending '{}' from gmail".format(msg))
class yahoo:
def send_email(self,msg):
print("sending '{}' from yahoo".format(msg))
class email:
provider=gmail()
def set_provider(self,provider):
self.provider=provider
def send_email(self,msg):
self.provider.send_email(msg)
client1=email()
client1.send_email("Hello")
client1.set_provider(yahoo())
client1.send_email("Hello")
Output:
sending 'Hello' from gmail
sending 'Hello' from yahoo
Customization via Inheritance specializing inherited methods:
• The tree-searching model of inheritance turns out to be a great way to specialize systems.
Because inheritance finds names in subclasses before it checks superclasses, subclasses can
replace default behavior by redefining the superclass's attributes.
• In fact, you can build entire systems as hierarchies of classes, which are extended by adding
new external subclasses rather than changing existing logic in place.
• The idea of redefining inherited names leads to a variety of specialization techniques.
• For instance, subclasses may replace inherited attributes completely, provide attributes that a
superclass expects to find, and extend superclass methods by calling back to the superclass
from an overridden method.
20
Padmashri Dr. Vitthalrao Vikhe Patil Institute Of Technology & Engineering (Polytechnic ), Pravaranagar
PWP-22616,BD
21
Padmashri Dr. Vitthalrao Vikhe Patil Institute Of Technology & Engineering (Polytechnic ), Pravaranagar
PWP-22616,BD
print("in extender.method")
class provider(super): # fill in a required method
def action(self):
print("in provider.action“)
for klass in (inheritor,replacer,extender):
print("\n"+klass.__name__+"...")
klass().method()
print("\n provider...")
x=provider()
x.delegate()
Output:
inheritor...
in super.method
provider...
replacer...
in replacer.method
provider...
extender...
in super.method
in extender.method
provider...
in provider.action
• When we call the delegate method through provider instance, two independent inheritance
searches occur:
• On the initial x.delegate call, Python finds the delegate method in Super, by searching at the
provider instance and above. The instance x is passed into the method's self argument as usual.
• Inside the super.delegate method, self.action invokes a new, independent inheritance search at
self and above. Because self references a provider instance, the action method is located in the
provider subclass.
22