PYTHON PROGRAMMING OBJECT ORIENTED PROGRAMMING
Chapter 3
OBJECT ORIENTED PROGRAMMING
Python is an object-oriented language since its beginning. It allows us to develop
applications using an Object-Oriented approach. In Python, we can easily create and
use classes and objects.
Major principles of object-oriented programming system are given below,
➢ Class:
A Class represents a set of objects that shares common characteristics and
behaviour.
➢ Object:
An object is a real world entity / real world identifiable entity which represent
characteristics, state and behaviour.
➢ Inheritance:
In OOP, the concept of inheritance provides the idea of reusability. This means that
we can add additional features to an existing class without modifying it. This is
possible by deriving a new class form the existing one.
➢ Polymorphism:
Polymorphism means the ability to take more than one form. An operation may
exhibit different behavior in different instance. The behavior depends upon the type
of data used in the operation.
➢ Method
The method is a function that is associated with an object. In Python, a method is
not unique to class instances.
➢ Data Abstraction
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.
➢ Encapsulation
The wrapping up of data and method into a single unit is known as Encapsulation.
The data is not accessible to the outside world and only those methods, which are
wrapped in the class, can access it. These methods provide the interface between
the object data and the program.
----------------------------------------------------------------------------------------
CLASS
Class defined as collection of objects, that has some specific attributes and
methods.
Creating a class
Creating a class in Python with the following syntax:
Class classname:
<method definition-1>
<method definition-n>
JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 1
PYTHON PROGRAMMING OBJECT ORIENTED PROGRAMMING
Example:
Class student:
Reg=1234
Name=”aaa”
def display(self):
print([Link])
print([Link])
----------------------------------------------------------------------------------------------------------------------------- --------------
OBJECT
“An object is a real world entity / run time entity which represent
characteristics, state and behavior”.
In other words, Object is a variable of type class or object is an instance, which
represents the characteristics of a class.
Syntax:
objname=classname(args)
Example:
Class student:
Reg=1234
Name=”aaa”
def display(self):
print([Link])
print([Link])
stu=student();
[Link]();
---------------------------------------------------------------------------------
SELF PARAMETER
▪ The self is used as a reference variable, which refers to the current class object.
▪ It is used to access variables which belong to same class.
▪ We can use anything instead of self, but it must be the first parameter of any function
which belongs to the class.
Example:
Class student:
Reg=1234
Name=”aaa”
def display(self):
print([Link])
print([Link])
stu=student()
[Link]()
METHODS
The class functions are known by common name, methods. In Python, methods
are defined as part of the class definition and are invoked only by an instance.
To call a method we have to :
▪ Define the class (and the methods),
▪ Create an instance, and finally,
▪ Invoke the method from that instance.
JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 2
PYTHON PROGRAMMING OBJECT ORIENTED PROGRAMMING
Here is an example class with a method:
class first:
def display(self):
print(“welcome”)
The self is a parameter that references the object itself. Using self, you can
access object’s members in a class definition.
To invoke the method we have to instantiate the class and call the method as follows.
obj=first()
[Link]()
-----------------------------------------------------------------------------------------------
_ _init_ _( ) method:
Each class associated with the function called _ _init_ _( ) function which is
always executed when the class being created.
This function which is always executed when the class being creating. Using the
function we can assign/access class variable.
class student:
def _ _init_ _(self,reg,name):
[Link]=reg
[Link]=name
def display(self):
print([Link])
print([Link])
stu=student(“1234”,”aaa”)
[Link]()
--------------------------------------------------------------------------------------------
INHERITANCE
▪ Inheritance provides code reusability.
▪ “Inheritance is a process of creating new class from an existing class. The
new class is called the derived class or subclass or child class. The existing
class is called the base class or super class or parent class.
▪ The derived class inherits all the properties of the base class and it can add new
features of its own.
▪ The derived class members automatically inherit the features of the base class.
▪ The derived class may also posses additional features, apart from those inherited
from the base class.
▪ A class could be derived from different base classes.
Syntax:
class BaseClassName():
<statement-1>
..
<statement-N>
class DerivedClassName(BaseClassName):
<statement-1>
. .<statement-N>
JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 3
PYTHON PROGRAMMING OBJECT ORIENTED PROGRAMMING
Example:
class First:
def input(self):
self.a = int(input("Enter first number:"))
self.b = int(input("Enter second number:"))
class Second(First):
def add(self):
self.z = self.a + self.b
print("Sum of two numbers:", self.z)
obj = Second()
[Link]()
[Link]()
TYPES OF INHERITANCE
➢ Single level Inheritance
➢ Multi level inheritance
➢ Multiple inheritances
➢ Hierarchical inheritance
➢ Hybrid inheritance
Single level Inheritance
It contains only one base class and only one derived class. One parent class one child
class.
Syntax:
class BaseClassName():
<statement-1>
..
<statement-N>
class DerivedClassName(BaseClassName):
<statement-1>
..
<statement-N>
Example:
class First:
def input(self):
self.a = int(input("Enter first number:"))
self.b = int(input("Enter second number:"))
class Second(First):
JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 4
PYTHON PROGRAMMING OBJECT ORIENTED PROGRAMMING
def add(self):
self.z = self.a + self.b
print("Sum of two numbers:", self.z)
obj = Second()
[Link]()
[Link]()
Multi level inheritance
If a class is derived from another derived class, It is called multilevel inheritance.
Syntax
class BaseClassName():
<statement-1>
..
<statement-N>
class DerivedClassName(BaseClassName):
<statement-1>
..
<statement-N>
class DerivedClassName (DerivedClassName):
<statement-1>
..
<statement-N>
Example:
class First:
def input(self):
self.a = int(input("Enter first number:"))
self.b = int(input("Enter second number:"))
class Second(First):
def add(self):
self.z = self.a + self.b
JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 5
PYTHON PROGRAMMING OBJECT ORIENTED PROGRAMMING
class Third(Second):
def result(self):
print("Sum of two numbers:", self.z)
obj = Third()
[Link]()
[Link]()
[Link]()
Multiple inheritances: -
If a class is derived from more than one base class, it is called multiple inheritances.
Syntax
class BaseClassName ():
<statement-1>
..
<statement-N>
class BaseClassName (object):
<statement-1>
..
<statement-N>
class DerivedClassName(BaseClassName 1, BaseClassName 2):
<statement-1>
..
<statement-N>
Example:
class First:
def input1(self):
self.x = int(input("Enter first number:"))
class Second:
def input2(self):
self.y = int(input("Enter second number:"))
class Third(First, Second):
JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 6
PYTHON PROGRAMMING OBJECT ORIENTED PROGRAMMING
def add(self):
super().input1()
super().input2()
self.z = self.x + self.y
print("Sum is:", self.z)
obj = Third()
[Link]()
Hierarchical inheritance: -
The process of inheriting the properties of one base class by more than one derived
class is called hierarchical inheritance.
Syntax
class BaseClassName(object):
<statement-1>
..
<statement-N>
class DerivedClassName1(BaseClassName):
<statement-1>
..
<statement-N>
class DerivedClassName2(BaseClassName):
<statement-1>
..
<statement-N>
Example:
class First:
def input(self):
self.a = int(input("Enter first number:"))
self.b = int(input("Enter second number:"))
class Second(First):
def add(self):
self.z = self.a + self.b
print("Sum of two numbers:", self.z)
JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 7
PYTHON PROGRAMMING OBJECT ORIENTED PROGRAMMING
class Third(First):
def mul(self):
self.z = self.a * self.b
print("Product of two numbers:", self.z)
obj1 = Second()
[Link]()
[Link]()
obj = Third()
[Link]()
[Link]()
Hybrid inheritance: -It is a combination of single, hierarchical, multiple and multi-
level inheritance.
Here A is the base class, B and C are the derived classes of A. B and C are the base
class of D. D is the base class of E.
----------------------------------------------------------------------------------------------------------------------------------------
Constructor: [ init () ]method
▪ A Constructor is a special method, which is executed automatically when an object
is created.
▪ Constructor is used to initialize the instance variable of a class.
▪ In constructor, we create the instance variable and initialize them with some starting
values.
▪ The first parameter of the constructor will be ‘self’ variable that contains the memory
address of the instance.
▪ The python provides a special method, init is a constructor. This method, known as
an initializer, is invoked to initialize a new object’s state when it is created.
▪ An initializer can perform any action, but initializers are designed to perform
initializing actions, such as creating an object’s data fields with initial values.
JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 8
PYTHON PROGRAMMING OBJECT ORIENTED PROGRAMMING
There are two types of constructor,
➢ default constructor
➢ parameterized constructor
default Constructor
If we are creating any constructor externally the python interpreter automatically
provide default constructor.
Example:
class student:
def __init__(self):
[Link] = 1234
[Link] = "aaa"
print([Link])
print([Link])
obj=student()
without invoking any method program executes.
Parameterized Constructor
It is a constructor which having parameter, while at the time of creating the
object, we can pass the data for constructor.
Example:
class student:
def __init__(self,reg,name):
[Link]=reg
[Link]=name
def display(self):
print([Link])
print([Link])
obj=student("1234","aaa")
[Link]()
----------------------------------------------------------------------------------------------------------------------------- --------
Destructor [ del () ]Method :
▪ A destructor is a special method, which is executed automatically when an object
scope is ended.
▪ Like constructor, there is an equivalent destructor special method called __del__().
▪ Due to the way Python manages garbage collection of objects, this function is not
executed until all references to an instance object have been removed.
▪ Destructors in Python are methods which provide special processing before instances
are de-allocated and are not commonly implemented since instances are rarely de-
allocated explicitly.
Example:
JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 9
PYTHON PROGRAMMING OBJECT ORIENTED PROGRAMMING
class xyz(object):
def init (self): # Constructor print (“Object is created and Initialize”)
def del (self): # Destructor print(“xyz object is deleted / Destructor is
executed”)
K=xyz() # Constructor call
del K # Destructor call
-------------------------------------------------------------------------------------------------------------------------------------------
METHOD OVERRIDING
If subclass (child class) has the same method as declared in the parent class, it
is known as method overriding.
Example program to illustrate Method overriding:
class Employee:
def message(self):
print('This message is from Employee Class')
class Department(Employee):
def message(self):
print('This Department class is inherited from Employee')
emp = Employee()
[Link]()
print('------------')
dept = Department()
[Link]()
In this example,
– we created an employee class, which contains a message method that prints a
message.
– Next, we created a department class that inherits from Employee class.
– Within this class, we created a method with the same name message with a
different print message.
– The emp object is printing a string from the Employee class message function.
– Whereas, [Link]() is a printing test from Department class.
----------------------------------------------------------------------------------------------
METHOD OVERLOADING
If the process of defining two or more methods are having same name with
different arguments.
Python doesn’t support method overloading directly. Alternative solution to achieve
overloading in python,
Class student
def _ _init_ _(self,n1,n2):
self.n1=n1
self.n2=n2
def sum(self,a,b):
s=0
def sum(self, a=None, b=None, c=None):
JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 10
PYTHON PROGRAMMING OBJECT ORIENTED PROGRAMMING
if a!=None and b!=None and c!=None:
s=a+b+c
elif a!=None and b!=None
s=a+b
else:
s=a
print(s)
stu=student(50,60)
stu=sum(4,9,11)
------------------------------------------------------------------------------------------
PACKAGE
▪ Packages are a way of structuring many packages and modules which helps in a
well-organized hierarchy of data set, making the directories and modules easy to
access.
▪ Just like there are different drives and folders in an OS to help us store files,
similarly packages help us in storing other sub-packages and modules, so that it
can be used by the user when necessary.
Creating Packages
To create a package in Python, we need to follow these three simple steps:
➢ First, we create a directory and give it a package name, preferably related to
its operation.
➢ Then we put the classes and the required functions in it.
➢ Finally we create an __init__.py file inside the directory, to let Python know that
the directory is a package.
Example of Creating Package
Let’s create a package named Cars and build three modules in it namely, Bmw,
Audi and Nissan.
Below steps and example Python code to illustrate the Modules
– First we create a directory and name it Cars.
– Then we need to create modules.
To do this we need to create a file with the name [Link] and create its content by
putting this code into it.
#Python code to illustrate the Module Audi
class Bmw:
def __init__(self):
[Link] = ['i8', 'x1', 'x5', 'x6']
def outModels(self):
print('These are the available models for BMW')
for model in [Link]:
print('\t%s ' % model)
Then we create another file with the name [Link] and add the similar type of code
to it with different members.
JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 11
PYTHON PROGRAMMING OBJECT ORIENTED PROGRAMMING
#Python code to illustrate the Module Audi
class Audi:
def __init__(self):
[Link] = ['q7', 'a6', 'a8', 'a3']
def outModels(self):
print('These are the available models for Audi')
for model in [Link]:
print('\t%s ' % model)
Then we create another file with the name [Link] and add the similar type of code
to it with different members.
# Python code to illustrate the Module
class Nissan:
def __init__(self):
[Link] = ['altima', '370z', 'cube', 'rogue']
def outModels(self):
print('These are the available models for Nissan')
for model in [Link]:
print('\t%s ' % model)
– Finally we create the __init__.py file. This file will be placed inside Cars
directory and can be left blank or we can put this initialisation code into it.
from Bmw import Bmw
from Audi import Audi
from Nissan import Nissan
– Now, let’s use the package that we created.
To do this make a [Link] file in the same directory where Cars package is located
and add the following code to it:
# Import classes from your brand new package
from Cars import Bmw
from Cars import Audi
from Cars import Nissan
# Create an object of Bmw class & call its method
ModBMW = Bmw()
[Link]()
# Create an object of Audi class & call its method
JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 12
PYTHON PROGRAMMING OBJECT ORIENTED PROGRAMMING
ModAudi = Audi()
[Link]()
# Create an object of Nissan class & call its method
ModNissan = Nissan()
[Link]()
JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 13