L-6 OOPs with Python
L-6 OOPs with Python
1
Session Overview
OOPS in Python
Exercise
2
OOPS in Python
❖ It allows us to develop applications using an Object Oriented approach using classes and objects.
❑ Data Abstraction
❑ Encapsulation
❑ Polymorphism
❑ Inheritance
❑ Data Hiding
3
Data Abstraction
❖For example, a method that adds two integers. The internal processing
object-oriented programming.
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
❖ 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
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?
❑Parameterized Constructor
❑Non-parameterized Constructor
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
❖ "__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.
❖ 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 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
❑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.
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 ')
❖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.
❖ 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 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 −
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 getAttr(self):
print ("Parent attribute :", Parent.parentAttr)
def childMethod(self):
print ('Calling child method')
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!!