0% found this document useful (0 votes)
8 views

L-6 OOPs with Python

Uploaded by

omvati343
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

L-6 OOPs with Python

Uploaded by

omvati343
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 43

OOPs in Python

OOPs concepts with Applications

Trainer: Ms. Nidhi Grover Raheja

1
Session Overview

OOPS in Python

Classes and Objects

Constructors and Destructors

OOPs concept in details

Exercise

2
OOPS in Python

❖ Python is an object-oriented programming language.

❖ It allows us to develop applications using an Object Oriented approach using classes and objects.

❖ Some OOPs concepts:

❑ Class and Object

❑ Data Abstraction

❑ Encapsulation

❑ Polymorphism

❑ Inheritance

❑ Data Hiding

3
Data Abstraction

❖Data Abstraction is the concept of hiding the internal details and

describing things in simple terms.

❖For example, a method that adds two integers. The internal processing

of the method is hidden from the outer world.

❖ There are many ways to achieve abstraction in object-oriented

programming, such as encapsulation and inheritance.


12
Encapsulation

❖Encapsulation is the technique used to implement abstraction in

object-oriented programming.

❖Encapsulation is used for access restriction to class members and

methods.

13
Class and Objects
What is a class and it’s object?

❖ A Class is a user-defined prototype for an object that defines a set of attributes that characterize any object of the class. It

encapsulates or binds together the data members (class variables and instance variables) and methods that use these data

members together in one unit.

❖ A class contains data members and methods that use that data members.

❖ An Object is the instance of a class and the process of creation of an object i.e. instance of a class is called Instantiation.

Example: An object obj1 that belongs to a class say, Rectangle, for example, is an instance of the class Rectangle.

❖ The method __init__() is a special method, which is called class constructor or initialization method that Python calls when

you create a new instance of this class.

28
Class and Objects (contd.)
Who are the members of a class?

❖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. Class variable would be accessed using class name.

❖Instance variable − A variable that is defined inside a method and belongs only to the current
instance of a class.

❖Data member − A class variable or instance variable that holds data associated with a class and its
objects.

❖Method − A function that is defined in a class definition and is using data members of the class for
performing a specified task. A method is called with an object of class using dot operator.

29
Defining classes in Python
How to create a class?

❖ The class statement creates a new class definition. The name of the class immediately follows the
keyword class followed by a colon as follows −

❖ Syntax of class :

class ClassName:
'Optional class documentation string’
class_suite

Where:

❑ The class has a documentation string, which can be accessed via ClassName.__doc__.

❑ The class_suite consists of all the component statements defining class members, data attributes
and functions.

30
Object Instantiation using Constructors
What is a constructor?

❖A constructor is a special type of method which is used to initialize the

instance members of the class.

❖Constructors can be of two types.

❑Parameterized Constructor

❑Non-parameterized Constructor

❖Constructor definition is executed when we create the object of this class.

31
Creating the constructor
How to create a constructor?

❖ In python, the method __init__() calls the constructor of the class. This method is called when the class is instantiated to

initialize the class attributes. Syntax:

• def __init__(self, arguments)

❖ "__init__" is a reserved method in python classes. It is known as a constructor in object oriented concepts. This method

called when an object is created from the class and it allow the class to initialize the attributes of a class.

❖ Here self represents the instance of the class. By using the "self" keyword we can access the attributes and methods of the

class in python.

❖ Any number of arguments can be passed depending upon __init__() definition.

❖ To create object instances of a class, we call the class using class name and pass in whatever arguments its __init__() method accepts.

32
Class & Object Example
Class & Object Demonstration

class Student:
'Common base class for all Students’ # A documentation string, which can be accessed via ClassName.__doc__
stuCount = 0 # class variable declared

def __init__(self, name, age):


self.name = name
self.age = age
Student.stuCount += 1

def displayCount(self):
print ("Total Students are %d" % Student.stuCount)

def displayStudent(self):
print ("Name : ", self.name, ", Age: ", self.age)

stu1 = Student(“Priya", 18) #This would create first object of Stude nt class"
stu2 = Student(“Smriti", 20) #This would create second object of Stud ent class"
stu1.displayStudent() # Calling method with object stu1
stu2.displayStudent () # Calling method with object stu2
print ("Total Students are %d" % Student.stuCount) # Accessing class variable stuCount shared by all objects

33
Use Destructors
How to use Destructors?

class Area:
def __init__( self, length=0, breadth=0):
self.length = length
self.breadth = breadth
def __del__(self):
class_name = self.__class__.__name__
print (class_name, “is now destroyed")

ar1 = Area()
ar2 = ar1
ar3 = ar1
print (id(ar1), id(ar2), id(ar3)) # prints the ids of the objects
del ar1 # delete ar1 object
del ar2 # delete ar2 object
del ar3 # delete ar3 object

34
Polymorphism

❖Polymorphism contains two words "poly" and "morphs". Poly means ‘many’ and

Morphs means ‘form’.

❖Polymorphism means that one task can be performed in multiple ways.

❖Implemented in two ways:

❑Overloading Methods

❑Overloading Operators

35
Method Overloading
Polymorphism through method calling

❖Overloading, in the context of programming, refers to the ability of a function or an operator to behave in
different ways depending on the parameters that are passed to the function, or the operands that the operator a
cts on.

❖Several ways to call a method is called polymorphism through method overloading. In Python you can define a
method in such a way that there are multiple ways to call a method.

❖Given a single method or function, we can specify the number of parameters during method calling.

❖Depending on the function definition, it can be called with zero, one, two or more parameters. This is known a
s method overloading.

❖Overloading a method fosters reusability. For instance, instead of writing multiple methods that differ only
slightly, we can write one method and overload it.

❖Overloading also improves code clarity and eliminates complexity.

36
Method Overloading (contd.)
Polymorphism through method calling

To overload a user-defined function in Python, we need to write the function logic in such a way that depending
upon the parameters passed, a different piece of code executes inside the function. Take a look at the following
example:

class Employee:
def greeting(self, name=None):
if name is not None:
print(‘Hello Employee: ' + name)
else:
print(‘Hello Guest ')

# Creating a class instance


emp = Employee()

# Call the method


emp.greeting()

# Call the method and pass a parameter


emp.greeting(‘Raman')
37
Operator Overloading
Polymorphism through operator overloading

❖When we use an operator on user defined data types then automatically a special function or
magic function associated with that operator is invoked. Changing the behavior of operator is as
simple as changing the behavior of method or function.

❖To perform operator overloading, Python provides some special function or Magic Function
that is automatically invoked when it is associated with that particular operator. For
example, when we use + operator, the magic method __add__ is automatically invoked in
which the operation for + operator is defined.

❖By changing this magic method’s code, we can give extra meaning to the + operator.

❖Suppose you have created a class to represent vectors. Suppose we want to use the simple
mathematical addition (+) operator to add them. Python does not allow this!!.

❖For this we must define an __add__ method in our class to perform vector addition and then the
addition operator (+) will add the two vectors in the same way as it adds two numbers: 38
Inheritance
Reusability using Inheritance

❖ Inheritance is the object-oriented programming concept where an object is based on another object.

❖ Inheritance is the mechanism of code reuse.

❖ The object that is getting inherited is called superclass and the object that inherits the superclass is called

subclass.

❖ Instead of starting from a scratch, you can create a class by deriving it from a pre-existing class by listing

the parent class in parentheses after the new class name.

❖ The child class inherits the attributes of its parent class, and you can use those attributes as if they were

defined in the child class. A child class can also override data members and methods from the parent.
39
Inheritance (contd.)
Syntax & Practical Demo

❖ Syntax:

❖ Derived classes are declared much like their parent class; however, a list of base classes to
inherit from is given after the class name −

class SubClassName (ParentClass1[, ParentClass2, ...]):


'Optional class documentation string'
class_suite

40
Inheritance (contd.)
Syntax & Practical Demo
class Parent: # define parent class
parentAttr = 100
def __init__(self):
print ("Calling parent constructor")

def parentMethod(self):
print ('Calling parent method')

def setAttr(self, attr):


Parent.parentAttr = attr

def getAttr(self):
print ("Parent attribute :", Parent.parentAttr)

class Child(Parent): # define child class


def __init__(self):
print ("Calling child constructor")

def childMethod(self):
print ('Calling child method')

c = Child() # instance of child


c.childMethod() # child calls its method
c.parentMethod() # calls parent's method
c.setAttr(200) # again call parent's method
41
c.getAttr() # again call parent's method
Multiple Inheritance
Many Parents for one class

We can drive a class from multiple parent classes as follows −

class X: # define your class X


.....

class Y: # define your class Y


.....

class Z(X, Y): # subclass of X and Y


.....

42
Data Hiding
Hide attribute details

❖ An object's attributes may or may not be visible outside the class definition.

❖ For hiding attribute’s visibility, name the attributes with a double underscore prefix, and those
attributes then will not be directly visible to outsiders.

❖ Example :

class Demo:
__hiddenCount = 0

def count(self):
self.__hiddenCount += 1
print (self.__hiddenCount)

d1 = Demo()
d1.count()
d1.count()
43
print (d1.__hiddenCount) # invokes error!!

You might also like