PP Unit-4
PP Unit-4
PART-2
Object Oriented Programming: Concept of class, object and instances, Constructor, class
attributes and destructors, Real time use of class in live projects, Inheritance, overlapping and
overloading operators, Adding and retrieving dynamic attributes of classes, Programming
using Oops support
Design with Classes: Objects and Classes, Data modelling Examples, Case Study An ATM,
Structuring Classes with Inheritance and Polymorphism
Introduction
We have two programming techniques namely
1. Procedural-oriented programming technique
2. Object-oriented programming technique
Till now we have using the Procedural-oriented programming technique, in which our
program is written using functions and block of statements which manipulate data. However a
better style of programming is Object-oriented programming technique in which data and
functions are combined to form a class. When compared to the programming techniques data
hiding, inheritance and exceptions handling are extra feature that oop have.so oop is better
when compared with pop.
Classes and objects are the main aspects of object oriented programming.
• Class − A user-defined prototype for an object that defines a set of attributes that
characterize any object of the class. The attributes are data members (class variables
and instance variables) and methods, accessed via dot notation.
• Class variable − A variable that is shared by all instances of a class. Class variables
are defined within a class but outside any of the class's methods. Class variables are
not used as frequently as instance variables are.
• Data member − A class variable or instance variable that holds data associated with a
class and its objects.
• Inheritance − The transfer of the characteristics of a class to other classes that are
derived from it.
• Instance − An individual object of a certain class. An object obj that belongs to a class
Circle, for example, is an instance of the class Circle.
• Object − A unique instance of a data structure that's defined by its class. An object
comprises both data members (class variables and instance variables) and methods.
Classes:
1. Class is a basic building block in python
2. Class is a blue print or template of a object
3. A class creates a new data type
4. And object is a instance(variable) of a the class
5. In python everything is an object or instance of some class
Example :
All integer variables that we define in our program are instances of class int.
>>> a=10
>>> type(a)
<class 'int'>
6. The python standard library based on the concept of classes and objects
Defining a class:
Python has a very simple syntax of defining a class.
Syntax :
Class class-name:
Statement1
Statement2
Statement3
-
-
-
Statement
From the syntax, Class definition starts with the keyword class followed by class-name and
a colon(:). The statements inside a class are any of these following
1. Sequential instructions
2. Variable definitions
3. Decision control statements
4. Loop statements
5. Function definitions
Example :
class ABC:
a=10
obj=ABC()
print(obj.a)
self variable and class methods:
• Self refers to the object itself ( Self is a pointer to the class instance )
• whenever we define a member function in a class always use a self as a first argument
and give rest of the arguments
• Even if it doesn’t take any parameter or argument you must pass self to a member
function
• We do not give a value for this parameter, when call the method, python will provide
it.
• The self in python is equivalent to the this pointer in c++
Example 1 :
class Person:
Destructor:
Destructors are called when an object gets destroyed. In Python, destructors are
not needed as much needed in C++ because Python has a garbage collector that
handles memory management automatically. The _ _ del _ _ ( ) method is a known as
a destructor method in Python. It is called when all references to the object have been
deleted i.e when an object is garbage collected.
def __del__(self):
# body of destructor
Note: A reference to objects is also deleted when the object goes out of reference or
when the program ends.
# Initializing
def __init__(self):
print('Employee created.')
obj = Employee()
del obj
Inheritance:
One of the major advantages of Object Oriented Programming is reusability.
Inheritance is one of the mechanisms to achieve the reusability. Inheritance is used to
implement is-a relationship.
Definition: A technique of creating a new class from an existing class is called inheritance. The
old or existing class is called base class or super class and a new class is called sub class or
derived class or child class.
The derived class inherits all the variable and methods of the base class and adds their
own variables and methods. In this process of inheritance base class remains unchanged.
Example 2:
class Person:
def __init__(self,name,age):
self.name=name
self.age=age
def display(self):
print("name=",self.name)
print("age=",self.age)
class Teacher(Person):
def __init__(self,name,age,exp,r_area):
Person.__init__(self,name,age)
self.exp=exp
self.r_area=r_area
def displayData(self):
Person.display(self)
print("Experience=",self.exp)
print("Research area=",self.r_area)
class Student(Person):
def __init__(self,name,age,course,marks):
Person.__init__(self,name,age)
self.course=course
self.marks=marks
def displayData(self):
Person.display(self)
print("course=",self.course)
print("marks=",self.marks)
print("********TEACHER***********")
t=Teacher("jai",55,13,"cloud computing")
t.displayData()
print("********STUDENT***********")
s=Student("hari",21,"B.Tech",99)
s.displayData()
Types of inheritance:
Python supports the following types of inheritan:
i) Single inheritance
ii) Multiple Inheritance
iii) Multi-level Inheritance
iv) Multi path Inheritance
Single Inheritance:
When a derived class inherits features form only one base class, it is called Single
inheritance.
Syntax:
class Baseclass:
<body of base class>
class Derivedclass(Baseclass):
<body of the derived class>
Example:
class A:
i=10
class B(A):
j=20
obj=B()
print("memeber of class A is",obj.i)
print("memeber of class B is",obj.j)
Multiple Inheritance:
When derived class inherits features from more than one base class then it is called Multiple
Inheritance.
Syntax:
class Baseclass1:
<body of base class1>
class Baseclass2:
<body of base class2>
class Derivedclass(Baseclass1,Baseclass2):
<body of the derived class>
e.g.
class A:
i=10
class B:
j=20
class C(A,B):
k=30
obj=C()
print("memeber of class A is",obj.i)
print("memeber of class B is",obj.j)
print("memeber of class C is",obj.k)
Multi-Level Inheritance:
When derived class inherits features from other derived classes then it is called Multi-level
inheritance.
Syntax:
class Baseclass:
<body of base class>
class Derivedclass1(Baseclass):
<body of derived class 1>
class Derivedclass2(Derivedclass1):
<body of the derived class 2>
e.g.
class A:
i=10
class B(A):
j=20
class C(B):
k=30
obj=C()
print("memeber of class A is",obj.i)
print("memeber of class B is",obj.j)
print("memeber of class C is",obj.k)
Polymorphism in operators
• The + operator can take two inputs and give us the result depending on what the inputs
are.
• In the below examples we can see how the integer inputs yield an integer and if one of
the input is float then the result becomes a float. Also for strings, they simply get
concatenated.
Example:
a = 23
b = 11
c = 9.5
s1 = "Hello"
s2 = "There!"
print(a + b)
print(type(a + b))
print(b + c)
print(type (b + c))
print(s1 + s2)
print(type(s1 + s2))
We can also see that different python functions can take inputs of different types and then
process them differently. When we supply a string value to len() it counts every letter in it. But
if we five tuple or a dictionary as an input, it processes them differently.
Example:
str = 'Hi There !'
tup = ('Mon','Tue','wed','Thu','Fri')
lst = ['Jan','Feb','Mar','Apr']
dict = {'1D':'Line','2D':'Triangle','3D':'Sphere'}
print(len(str))
print(len(tup))
print(len(lst))
print(len(dict))
Polymorphism in inheritance:
Method Overriding:
It is nothing but same method name in parent and child class with different functionalities. In
inheritance only we can achieve method overriding. If super and sub classes have the same
method name and if we call the overridden method then the method of corresponding class
(by using which object we are calling the method) will be executed.
e.g.
class A:
i=10
def display(self):
print("I am class A and I hava data",self.i)
class B(A):
j=20
def display(self):
print("I am class B and I hava data",self.j)
obj=B()
obj.display()
Note: In above program the method of class B will execute. If we want to execute method of
class A by using Class B object we use super() concept.
Super():
In method overriding , If we want to access super class member by using sub class object we
use super()
e.g
class A:
i=10
def display(self):
print("I am class A and I hava data",self.i)
class B(A):
j=20
def display(self):
super().display()
print("I am class B and I hava data",self.j)
obj=B()
obj.display()
Note: In above example both the functions (display () in class A and display () in class B)
will execute
Note: Name mangling is the encoding of function and variable names into unique names so
that linkers can separate common names in the language.
overloading operators
Example 2:
class A:
def __init__(self, a):
self.a = a
class ATM:
def __init__(self):
self.balance=0
print("new account created")
def deposit(self):
amount=int(input("enter amount to deposit"))
self.balance=self.balance+amount
print("new balance is:",self.balance)
def withdraw(self):
amount=int(input("enter amount to withdraw"))
if self.balance<amount:
print("Insufficient Balance")
else:
self.balance=self.balance-amount
print("new balance is:",self.balance)
def enquiry(self):
print("Balance is:",self.balance)
a=ATM()
a.deposit()
a.withdraw()
a.enquiry()
Dynamic attributes in Python are terminologies for attributes that are defined at runtime, after
creating the objects or instances.
Example:
class EMP:
employee = True
e1 = EMP()
e2 = EMP()
e1.employee = False
e2.name = "SAI KUMAR"
print(e1.employee)
print(e2.employee)
print(e2.name)
# this will raise an error
# as name is a dynamic attribute
# created only for the e2 object
print(e1.name)