Object Oriented Programming
Nihar Ranjan Roy
nihar.ranjanroy@gdgoenka.ac.in, niharranjanroy@gmail.com Department of Computer Science and Engineering
GD Goenka University, Gurugram
Outline
1 Properties of OOP languages
2 Constructors
3 init():function
4 The Self parameter
5 Inbuilt Class functions
6 Built-in class attributes
7 Passing Object as parameter
8 Destructor del ()
9 Destructor del ()
10 class membership test
Classes and Objects I
Python is an object-oriented programming language. It allows us to develop applications using an Object Oriented approach.
Class
It is a logical entity that has some specific attributes and methods
Example:An Employee class may contain attributes and methods.
Attributes: email id, name, age, basicsalary,DateOfJoining.
Classes and Objects II
Object
An object is an entity that has state and behavior.
Everything in Python is an object, and almost everything has attributes and methods.
Python is an object oriented programming language.
Almost everything in Python is an object, with its properties and methods
All functions have a built-in attribute doc , which returns the doc
class syntax
In python, a class can be created by using the keyword class followed by the class name. The syntax to create a class is given below.
class ClassName:
<statement-1> .
.
Properties of OOP languages
Properties of Object Oriented Programming languages
Some of the properties of object oriented programming languages are:
Inheritance
Polymorphism
Abstraction
Properties of OOP languages
Python Classes/Objects
To create a class, use the keyword class: Example:
class Student:
name="Nihar" age=25
...
obj=Student() #creating an Object from the class
print(obj.name) #accessing member
Constructors
Constructors
A constructor is a special type of method (function) 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.
init():function
init():function
All classes have a function called init (), which is always executed
when the class is being initiated.
Use the init () function to assign values to object properties, or
other operations that are necessary to do when the object is being created:
The init () function is called automatically every time the class is
being used to create a new object.
class Student:
def __init__(selfref, name, age):
selfref.name = name selfref.age = age
p1 = Student("Nihar", 25) print(p1.name)
The Self parameter
The Self/selfref/this parameter
The first argument of every class method, including init, is always a reference to the current instance of the class.
By convention, this argument is always named self.
In the init method, self refers to the newly created object; in other class methods, it refers to the instance whose method was called.
However self is not a reserved keyword in python it’s just a strong convention. Many people say that why do we have to write self ? Why can’t we have it set automatically like in Java ?
The Self parameter
Object attributes and methods
Objects can also have methods like regular members
class Student:
name="" age=0
def __init__(selfref, name, age):
selfref.name = name selfref.age = age
def myfunc(selfref):
print("Hello my name is " + selfref.name)
Inbuilt Class functions
Inbuilt Class functions
The in-built functions defined in the class are
Function Description
getattr(obj,name,default) It is used to access the attribute of the object. setattr(obj, name,value) It is used to set a particular value to the specific
attribute of an object.
delattr(obj, name) It is used to delete a specific attribute.
Inbuilt Class functions
Example
class Student:
def __init__(self,name,id,age):
self.name = name;
self.id = id;
self.age = age
#creates the object of the class Student
s = Student("Nihar",100,32)
#prints the attribute name of the object s
print(getattr(s,'name'))
setattr(s,"age",23)# update value of attribute age to 23
print(getattr(s,'age'))# prints the modified value of age
# prints true if the student contains the attribute with name id
print(hasattr(s,'id'))
delattr(s,'age') # deletes the attribute age
# this will give an error since the attribute age has been deleted
Built-in class attributes
Built-in class attributes
Along with the other attributes, a python class also contains some built-in class attributes which provide information about the class.The built-in class attributes are
Attribute Description
class String name of class
dict It provides the dictionary containing the information about the class namespace.
doc It contains a string which has the class documentation name It is used to access the class name.
module It is used to access the module in which, this class is defined.
Built-in class attributes
Example
class Student:
def __init__(self,name,id,age):
self.name = name; self.id = id; self.age = age
def display_details(self):
print("Name:%s, ID:%d, age:%d"%(self.name,self.id)) s = Student("John",101,22)
Passing Object as parameter
Passing Object as parameter-I
#object comparison and passing object as parameter
class point:
x=0 y=0
def __init__(self,h,k):
self.x=h self.y=k
def disp(self):
print("x =",self.x, " y=",self.y)
def compObject(self,obj):
Passing Object as parameter
Passing Object as parameter-II
pt1=point(10,20) pt2=point(10,20) pt3=point(30,40)
print("Object1==Object2",pt1.compObject(pt2)) print("Object1==Object3",pt1.compObject(pt3))
Destructor del ()
Destructor
del ()
Like other OOP programming languages, python has a destructor too.
A destructor is a special function which is called when the object is about to die/ destroyed.
It is invoked one per instance.
Syntax
def __del__():\\
Destructor del ()
Destructor
del ():Example
#destructor
class point:
x=0 y=0
def __init__(self,h,k):
self.x=h self.y=k
def __del__(self):
print("I am dying ",id(self))
def disp(self):
print("x =",self.x, " y=",self.y) pt1=point(10,20)
del pt1
Output:
class membership test
class membership test
#class membership test
class A:
pass
class B:
pass
#Execution obj1=A() obj2=B()
Method Overloading in Python
Method Overloading in Python
#what if we overload method?
class point:
x=0 y=0 z=0
def __init__(self,h,k):
self.x=h self.y=k
def __init__(self,h,k,l):
self.x=h self.y=k self.z=l
Method Overloading in Python
Output:
Method Overloading in Python
Alternate way to perform Method Overloading in Python
#Method overloading
class Demo:
result=0
def add(self,instanceOf=None,*args): if instanceOf=="int":
result=0
if instanceOf=="str": result=""
for i in args:
result=result+i
return result
obj=Demo()
print("Adding integers",obj.add("int",10,20))
print("Adding strings",obj.add("str","my"," Name"," is"," Nihar"))
Operator Overloading
Operator Overloading I
Arithmetic Operator overloading via special functions
Operator Expression Internally
Addition p1 + p2 p1. add (p2)
Subtraction p1 - p2 p1. sub (p2)
Multiplication p1 * p2 p1. mul (p2)
Power p1 ** p2 p1. pow (p2)
Division p1 / p2 p1. truediv (p2)
Floor Division p1 // p2 p1. floordiv (p2)
Operator Overloading
Operator Overloading II
Comparison operator overloading
Table: Add caption
Operator Expression Internally
Less than p1<p2 p1. lt (p2)
Less than or equal to p1<= p2 p1. le (p2)
Equal to p1 == p2 p1. eq (p2)
Not equal to p1 ! = p2 p1. ne (p2)
Greater than p1>p2 p1. gt (p2)
Inheritance
Inheritance I
Simple Inheritance Multi Level Inheritance Multiple Inheritance
class A
class B
class A
class B
class C
class A class B
class C
class A: pass
class B(A): pass
class A: pass class B(A): pass class C(B): pass
Inheritance
issubclass(sub,sup) method
class Calculation1:
def Summation(self,a,b):
return a+b;
class Calculation2:
def Multiplication(self,a,b):
return a*b;
class Derived(Calculation1,Calculation2):
def Divide(self,a,b):
return a/b; d = Derived()
print(issubclass(Derived,Calculation2))
print(issubclass(Calculation1,Calculation2))
Inheritance
isinstance (obj, class) method
class Calculation1:
def Summation(self,a,b):
return a+b;
class Calculation2:
def Multiplication(self,a,b):
return a*b;
class Derived(Calculation1,Calculation2):
def Divide(self,a,b):
return a/b; d = Derived()
Inheritance
Method overriding
classBank:
defgetroi(self):
return10;
classBankX(Bank):
defgetroi(self):
return7;
classBankY(Bank):
defgetroi(self):
return8; b1=Bank() b2=BankX() b3=BankY()
print("Bank Rate of interest:",b1.getroi());
print("BankX Rate of interest:",b2.getroi());
print("BankY Rate of interest:",b3.getroi());
Output:
Inheritance
Data Abstraction
class Employee:
__count = 0;
def __init__(self):
Employee.__count = Employee.__count+1
def display(self):
print("The number of employees",Employee.__count) emp = Employee()
Exercises