0% found this document useful (0 votes)
54 views14 pages

PP Unit-4

Python

Uploaded by

Dwipendu Kundu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
54 views14 pages

PP Unit-4

Python

Uploaded by

Dwipendu Kundu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

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.

Overview of OOP Terminology

• 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.

• Function overloading − The assignment of more than one behavior to a particular


function. The operation performed varies by the types of objects or arguments
involved.
• Instance variable − A variable that is defined inside a method and belongs only to the
current instance of a class.

• 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.

• Instantiation − The creation of an instance of a class.

• Method − A special kind of function that is defined in a class definition.

• 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.

• Operator overloading − The assignment of more than one function to a particular


operator.

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

Note : the class members are accessed through class object


Note : class methods have access to all data contained in the instance of the object
Creating objects: ( creating an object of a class is known as class instantiation)
• Once a class is defined, the next job is to create a object of that class.
• The object can then access class variables and class methods using dot operator

Syntax of object creation:


Object-name=class-name()
• Syntax for accessing class members through the class object is
Object-name.class-member-name

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:

persons_count=0 # Class varibles


def setFullName(self,firstName,lastName):

self.firstName=firstName # instance variables


self.lastName=lastName # instance variables
persons_count+=1
def printFullName(self):
print(self.firstName," ",self.lastName)
print("Person number : ",Person.persons_count) #access Class variable
PersonName=Person()
PersonName.setFullName("vamsi","kurama")
PersonName.printFullName()
Constructor method:
A constructor is a special type of method (function) that is called when it instantiates an
object of a class. The constructors are normally used to initialize (assign values) to the instance
variables.
Creating a constructor: (The name of the constructor is always the _ _init_ _().)
The constructor is always written as a function called __init__(). It must always take as its first
argument a reference to the instance being constructed.
While creating an object, a constructor can accept arguments if necessary. When you create a
class without a constructor, Python automatically creates a default constructor that doesn't do
anything.
Every class must have a constructor, even if it simply relies on the default constructor.
Example:
class Person:
def _ _ init _ _(self):
self.firstName="xxx"
self.lastName="yyy"
def setFullName(self,firstName,lastName):
self.firstName=firstName
self.lastName=lastName
def printFullName(self):
print(self.firstName," ",self.lastName)
PersonName=Person()
PersonName.printFullName()
PersonName.setFullName("vamsi","kurama")
PersonName.printFullName()

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.

Syntax of destructor declaration:

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.

Example 1: Here is the simple example of destructor. By using del keyword we


deleted the all references of object ‘obj’, therefore destructor invoked automatically.
# Python program to illustrate destructor
class Employee:

# Initializing
def __init__(self):
print('Employee created.')

# Deleting (Calling destructor)


def __del__(self):
print('Destructor called, Employee deleted.')

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.

Syntax to inherit a class:


Class MySubClass(object):
Pass(Body-of-the-derived-class)
Example :
class Pet:
def __init__(self,name,age):
self.name=name
self.age=age
class Dog(Pet):
def sound(self):
print("I am {} and My age is {} and I sounds Like".format(self.name,self.age))
print("Bow Bow..")
class Cat(Pet):
def sound(self):
print("I am {} and My age is {} and I sounds Like".format(self.name,self.age))
print("Meow Meow..")
class Parrot(Pet):
def sound(self):
print("Hello I am {} and My age is {} ".format(self.name,self.age))
p1=Dog("Dozer",4)
p2=Cat("Edward",3)
p3=Parrot("Jango",6)
p1.sound()
p2.sound()
p3.sound()

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)

Multi Path Inheritance:


Syntax:
class Baseclass:
<body of the base class>
class Derived1(Baseclass):
<body of the derived1>
class Derived2(Baseclass):
<body of the derived2>
class Derived3(Derived1,Derived2):
<body of derived3>
e.g.
class A:
i=10
class B(A):
j=20
class C(A):
k=30
class D(B,C):
ijk=40
obj=D()
print("memeber of class A is",obj.i)
print("memeber of class B is",obj.j)
print("memeber of class C is",obj.k)
print("memeber of class C is",obj.ijk)
Polymorphism:
The word polymorphism means having many forms. In python we can find the same operator
or function taking multiple forms. That helps in re using a lot of code and decreases code
complexity.

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))

Polymorphism in in-built functions

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

Operator Overloading means giving extended meaning beyond their predefined


operational meaning. For example, operator + is used to add two integers as well as join two
strings and merge two lists. It is achievable because ‘+’ operator is overloaded by int class and
str class. You might have noticed that the same built-in operator or function shows different
behavior for objects of different classes, this is called Operator Overloading.

# Python program to show use of + and * operator for different purposes.


print(1 + 2)
# concatenate two strings
print("Learn"+"For")
# Product two numbers
print(3 * 4)
# Repeat the String
print("Learn"*4)
Output:
3
LearnFor
12
LearnLearnLearnLearn

Example 2:
class A:
def __init__(self, a):
self.a = a

# adding two objects


def __add__(self, o):
return self.a + o.a
ob1 = A(1)
ob2 = A(2)
ob3 = A("sai")
ob4 = A("kumar")
print(ob1 + ob2)
print(ob3 + ob4)

Case Study An ATM:

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()

Adding and retrieving dynamic attributes of classes:

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)

You might also like