Week-2 Day12 Oops
Week-2 Day12 Oops
OOP’S Concepts
Before knowing about the above 3 oop’s concepts, you have to know about what is a class and an
object?
What is a class?
What is an object?
1 For doubts about this document you can whatsapp me: Madhu.K(9912280626)
Now the question is what is blue-print and object in python
What is blue-print in any programming language?
2 For doubts about this document you can whatsapp me: Madhu.K(9912280626)
self.garage = None
Output:
House_1 object content
Garage: Cars
Kitchen: Things To Cook
Hall: Thigs to get relaxed
Living Area: Things to take rest
What is object?
Object creation
3 For doubts about this document you can whatsapp me: Madhu.K(9912280626)
Process of assigning values to the attributes of an object is called as object initialization.
Another example on class and object with object initialization and object state
class BykeDesign:
# special function
def __init__(self):
self.bykeNo = None
self.color = None
self.model = None
self.vendor = None
self.type = None
if __name__ == "__main__":
# We are creating new byke: means allocating memory for
the attributes defined using self with in __init__() method
# byke_1=1002
byke_1 = BykeDesign()
# To see the object state, call the show method
byke_1.show() # i ma calling show method by using
object called byke_1
# object initialization
byke_1.bykeNo = "AP169495"
byke_1.color = "White"
byke_1.vendor = "Hero"
byke_1.model = "2023"
4 For doubts about this document you can whatsapp me: Madhu.K(9912280626)
byke_1.type = "Electric Byke"
byke_1.show()
output:
Object state....
None
None
None
None
None
Object state....
AP169495
White
2023
Hero
Electric Byke
Constructor
What is a constructor?
1. In python a constructor is special function which is written in a class with name __init__ and
it must take atleast one argument.
2. Don’t call the constructors by using it’s name.
3. We call the constructors by using class name.
Types of constructors?
1. Non-parameterized constructors
2. Parameterized constructors
5 For doubts about this document you can whatsapp me: Madhu.K(9912280626)
What is instance(object) method?
1. Methods which are written in class and we can call them only by using objects.
What is object?
class Emp:
# constructor
# When the statements written in constructor will be
invoked
# Ans) at the time f calling
# don't call that constructor by using it's name
directly
# self=1002
# Note: assigning object or passing object means,
passing address of the object
def __init__(self):
# 1002.eno=None means we are telling the PVM to
allocate memory for eno at 1002 address and also telling to
assign a value None to it
self.eno = None
# 1002.ename=None means we are telling the PVM to
allocate memory for ename at 1002 address and also telling
to assign a value None to it
self.ename = None
# 1002.sal=None means we are telling the PVM to
allocate memory for sal at 1002 address and also telling to
assign a value None to it
self.sal = None
# self=e1
def setEmp(self):
self.eno = 1
self.ename = "Madhu.K"
self.sal = 200000.00
def display(self):
print("Eno:\t", self.eno)
6 For doubts about this document you can whatsapp me: Madhu.K(9912280626)
print("Ename:\t", self.ename)
print("Salary:\t", self.sal)
def setEmp(self,eno1,ename1,sal1):
#self
self.eno=eno1
self.ename=ename1
self.sal=sal1
def show(self):
print("Employee details........")
7 For doubts about this document you can whatsapp me: Madhu.K(9912280626)
print("Eno:\t",self.eno)
print("Ename:\t",self.ename)
print("Sal:\t",self.sal)
e1=Emp()
e1.setEmp(1,"Ranjith",300000.00)
#Emp.setEmp(e1,1,"Ranjith",300000.00)
e1.show()
#Emp.show(e1)
Output:
Employee details........
Eno: 1
Ename: Ranjith
Sal: 300000.0
How many times memory will be allocated for the attributes declared by using self?
1. No.of times which is equals to the no.of times you have created object
2. For every object creation memory will be allocated for the attributes declared by using self.
3. These are called as instance variables in other languages.
4. These attributes will be created each time the new object is created by PVM
def show(self):
print("Employee details........")
print("Eno:\t",self.eno)
print("Ename:\t",self.ename)
print("Sal:\t",self.sal)
8 For doubts about this document you can whatsapp me: Madhu.K(9912280626)
e1=Emp(1,"Ranjith",300000.00)
#Emp.__init__(1002,1,"Ranjith",300000.00)
#Emp.__init__(e1,1,"Ranjith",300000.00)
e2=Emp(2,"Akshitha",400000.00)
#Emp.__init__(e2,2,"Akshitha",400000.00)
#Emp.__init__(2002,2,"Akshitha",400000.00)
e3=Emp(3,"Ranjith",500000.00)
#Emp.__init__(e3,3,"Ranjith",500000.00)
#Emp.__init__(3002,3,"Ranjith",500000.00)
e1.show()
e2.show()
e3.show()
output:
Ename: Ranjith
Sal: 300000.0
Employee details........
Eno: 2
Ename: Akshitha
Sal: 400000.0
Employee details........
Eno: 3
Ename: Ranjith
Sal: 500000.0
Static variables
What is static variables?
1. It is a variable which is declared within a class and out side the methods.
2. Static variables are created only once. And this variable can be shared or accessed by all the
objects.
3. It is a common variable for all the objects.
4. We can access static variable by using class name
5. Static variables are create during class loads into method area(memory)
9 For doubts about this document you can whatsapp me: Madhu.K(9912280626)
1. It is a variable which is declared by using object.
2. Instance variables are create by the PVM for every object creation
3. Instance variables are create each time a new object is created by the PVM.
4. We can access instance variables by using object
Class will be loaded by PVM only once, that can be used any no.of times during program execution.
Instance method
10 For doubts about this document you can whatsapp me: Madhu.K(9912280626)
One.s = 10
obj1.show()
# One.show(obj1)
obj2.show()
# One.show(obj2)
Output:
s: 10
Object state...................
self.a: 1000
self.b: 2000
s: 10
Object state...................
self.a: 3000
self.b: 4000
11 For doubts about this document you can whatsapp me: Madhu.K(9912280626)
# it is called as instance method
def show(self):
print(f"Object {self.count}
state...................")
print("self.a:\t", self.a)
print("self.b:\t", self.b)
output:
Object 1 state...................
self.a: 1000
self.b: 2000
Object 2 state...................
self.a: 3000
self.b: 4000
Inheritance
What is inheritance?
Process of including members(methods, and properties or attributes) from one class to another
class, is called as inheritance.
Advantage
12 For doubts about this document you can whatsapp me: Madhu.K(9912280626)
Forms of inheritance
If a child class inherits only one base class at a time it is called as simple or single level inheritance.
If a single child class inherits, more than one base class at a time it is called as multiple inheritance.
13 For doubts about this document you can whatsapp me: Madhu.K(9912280626)
print("Object state....")
print("self.a:\t", self.a)
print("self.b:\t", self.b)
class Child(Base):
pass
output:
Base class constructor...
Object state....
self.a: 100
self.b: 200
Yes, But the latest method overrides or replaces the older method. Means at a time a class contains
a single method with same name in python.
class Base:
# constructor
def __init__(self, a, b):
print("Base class parameterized constructor...")
self.a = a
self.b = b
14 For doubts about this document you can whatsapp me: Madhu.K(9912280626)
# object method or instance method
# self=1002
def show(self):
print("Object state....")
print("self.a:\t", self.a)
print("self.b:\t", self.b)
class Child(Base):
pass
cobj.show()
# Child.show(cobj)
Output:
Base class non parameterized constructor....
Object state....
self.a: 100
self.b: 200
1. It is also a special function which will be invoked by Garbage Collector, wheneven object is is
in out of scope.
2. If the objects are not in out of scope, then all the objects will definitely get deleted
whenever the program ends.
3. Destructors will be invoked, at the time of object get destroyed
15 For doubts about this document you can whatsapp me: Madhu.K(9912280626)
Let us say we have opened a file in a constructor, and i want to close that file whenever the object
get destroyed, how we can do that?
1. Garbage Collector actually destroys the objects which are in out of scope
If you want the base method in child with different implementation, then we override a method in
child class.
Other forms of inheritances(all these forms are extended forms of basic forms)
1. Multi-level inheritance
2. Hierarchical inheritance
3. Hybrid inheritance
Hierarchical Inheritance
1. If a single base class is inherited by morethan one child class it is called as Hierarchical
inheritance.
2. It is the extended form of single level inheritance
Example on hierarchical inheritance, method overriding, and destructors and scopes of objects
class Bird:
# parameterized constructor
def __init__(self, breed, name, color):
16 For doubts about this document you can whatsapp me: Madhu.K(9912280626)
self.breed = breed
self.name = name
self.color = color
def makeNoise(self):
print(self.name, " Makes noise")
def fly(self):
print(self.name, "can fly")
def __del__(self):
print("Object is deleted...")
class Sparrow(Bird):
def makeNoise(self):
print(self.name, " Chirps")
class Ostrich(Bird):
def fly(self):
print(self.name, " Can't Fly")
def makeNoise(self):
print(self.name, " is Booming")
fun1()
print("welcome...")
17 For doubts about this document you can whatsapp me: Madhu.K(9912280626)
print("welcome...")
print("welcome...")
o1 = Ostrich("Struthionidae", "Ostrich", "Black & White")
o1.makeNoise()
o1.fly()
output:
Parrot Makes noise
Parrot can fly
Sparrow Chirps
Sparrow can fly
Object is deleted...
welcome...
welcome...
welcome...
Ostrich is Booming
Ostrich Can't Fly
Object is deleted...
Object is deleted...
Example on multi-level inheritance and calling base class overridden method in child class method
class Base:
def __init__(self, a):
self.a = a
18 For doubts about this document you can whatsapp me: Madhu.K(9912280626)
def display(self):
print("self.a:\t", self.a)
class Child(Base):
def __init__(self, a, b):
self.a = a
self.b = b
def display(self):
super().display()
print("self.b:\t", self.b)
class SubChild(Child):
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
def display(self):
# Child.display(self)
super().display()
print("self.c:\t", self.c)
output:
19 For doubts about this document you can whatsapp me: Madhu.K(9912280626)
b1 object state..........
self.a: 10
c1 object state..........
self.a: 100
self.b: 200
sc1 object state..........
self.a: 1000
self.b: 2000
self.c: 3000
def show(self):
print("self.a:\t", self.a)
print("self.b:\t", self.b)
class Child(Base):
# self=1002
# a=100
# b=200
# c=300
# d=400
def __init__(self, a, b, c, d):
# we are calling Base class constructor in child
class constructor without using super() function, but we
have to pass the present object explicitly
#Base.__init__(self, a, b)
# we can call the base class constructor in child
class constructor by using super() function, but no need to
pass present object(self) explicitly
20 For doubts about this document you can whatsapp me: Madhu.K(9912280626)
# implicitly the present object will be passed to
the Base class constructor
super().__init__(a, b)
self.c = c
self.d = d
1. Static methods
2. Class methods
21 For doubts about this document you can whatsapp me: Madhu.K(9912280626)
"""
1. I have written the class One to give demo on class
and static methods
2. It also has a static variable s
3. I have written constructor and also destructor in
this class
"""
s = 0
@staticmethod
def fun1():
print("static method....")
print("One.s:\t", One.s)
@staticmethod
def fun2(s):
print("static method....")
One.s = s
print("One.s:\t", One.s)
@classmethod
def fun3(cls):
print(".........fun3............")
print("class name:\t", cls.__name__)
print("class dictionary:\t", cls.__dict__)
print("class documentation:\t", cls.__doc__)
cls.s = 10000
print("cls.s:\t", cls.s)
def __del__(self):
print("I am gonna die...I am gonna die...I am dead")
o1 = One(100, 200)
22 For doubts about this document you can whatsapp me: Madhu.K(9912280626)
# i m calling static method by using object
o1.fun1()
o1.fun2(10)
o1.fun3()
One.fun3()
Output:
constructor........
static method....
One.s: 0
static method....
One.s: 10
static method....
One.s: 10
static method....
One.s: 100
.........fun3............
class name: One
class dictionary: {'__module__': '__main__',
'__doc__': '\n 1. I have written the class One to give
demo on class and static methods\n 2. It also has a
static variable s\n 3. I have written constructor and
also destructor in this class\n ', 's': 100, '__init__':
<function One.__init__ at 0x000001BAF47FC9A0>, 'fun1':
<staticmethod(<function One.fun1 at 0x000001BAF47FD800>)>,
'fun2': <staticmethod(<function One.fun2 at
0x000001BAF47FD8A0>)>, 'fun3': <classmethod(<function
One.fun3 at 0x000001BAF47FD940>)>, '__del__': <function
One.__del__ at 0x000001BAF47FD9E0>, '__dict__': <attribute
'__dict__' of 'One' objects>, '__weakref__': <attribute
'__weakref__' of 'One' objects>}
class documentation:
23 For doubts about this document you can whatsapp me: Madhu.K(9912280626)
1. I have written the class One to give demo on class
and static methods
2. It also has a static variable s
3. I have written constructor and also destructor in
this class
cls.s: 10000
.........fun3............
class name: One
class dictionary: {'__module__': '__main__',
'__doc__': '\n 1. I have written the class One to give
demo on class and static methods\n 2. It also has a
static variable s\n 3. I have written constructor and
also destructor in this class\n ', 's': 10000,
'__init__': <function One.__init__ at 0x000001BAF47FC9A0>,
'fun1': <staticmethod(<function One.fun1 at
0x000001BAF47FD800>)>, 'fun2': <staticmethod(<function
One.fun2 at 0x000001BAF47FD8A0>)>, 'fun3':
<classmethod(<function One.fun3 at 0x000001BAF47FD940>)>,
'__del__': <function One.__del__ at 0x000001BAF47FD9E0>,
'__dict__': <attribute '__dict__' of 'One' objects>,
'__weakref__': <attribute '__weakref__' of 'One' objects>}
class documentation:
1. I have written the class One to give demo on class
and static methods
2. It also has a static variable s
3. I have written constructor and also destructor in
this class
cls.s: 10000
I am gonna die...I am gonna die...I am dead
Factory methods
24 For doubts about this document you can whatsapp me: Madhu.K(9912280626)
def __init__(self, a, b):
print("constructor...")
self.a = a
self.b = b
@classmethod
def factory(cls, x, y):
# we can't create objects by using class name in
class method
obj = cls(x, y)
#obj = One(100, 200)
return obj
def display(self):
print("Object state...")
print("a:\t", self.a)
print("b:\t", self.b)
def __del__(self):
print("destructor")
output:
constructor...
constructor...
constructor...
Object state...
a: 10
b: 20
Object state...
a: 100
25 For doubts about this document you can whatsapp me: Madhu.K(9912280626)
b: 200
Object state...
a: 1000
b: 2000
destructor
destructor
destructor
Multiple inheritance
If a single child class inherits morethan one base class at a time, it is called as multiple inheritance
def fun1(self):
print("fun1() of Base1 method")
class Base2:
def __init__(self, x, y):
self.x = x
self.y = y
# instance methods
def fun2(self):
print("fun2() of Base2 method")
c1 = Child(10, 20)
c1.fun1()
c1.fun2()
output:
26 For doubts about this document you can whatsapp me: Madhu.K(9912280626)
fun1() of Base1 method
fun2() of Base2 method
def fun1(self):
print("fun1() of Base1 method")
print("a:\t", self.a)
class Base2:
def __init__(self, x, y):
print("Base-2 constructor")
self.x = x
self.y = y
# instance methods
def fun2(self):
print("fun2() of Base2 method")
print("x:\t", self.x)
print("y:\t", self.y)
output:
Child 1 constructor
27 For doubts about this document you can whatsapp me: Madhu.K(9912280626)
Base-1 constructor
Base-2 constructor
fun1() of Base1 method
a: 10
fun2() of Base2 method
x: 20
y: 30
Process of hiding un-necessary details from the end user and providing necessary details is called as
data abstraction.
1. In python we don’t have any keywords to define private attributes, but we have to follow a
naming convention, to make an attribute private which is __(double underscore)
28 For doubts about this document you can whatsapp me: Madhu.K(9912280626)
# protected attributes in general are accessible
only within the class and child classes, but in python it is
given for readability purpose only it won't work
self._d = 40
class Child(One):
pass
if __name__ == "__main__":
obj1 = One()
# we can't access __a because it is private
# print(obj1.__a)
print(obj1.c)
# we can't access/call __fun1() because it is private
# obj1.__fun1()
Output:
30
def __sum(self):
return
self.__s1+self.__s2+self.__s3+self.__s4+self.__s5
29 For doubts about this document you can whatsapp me: Madhu.K(9912280626)
def __isPass(self):
if self.__s1 >= 40 and self.__s2 >= 40 and self.__s3
>= 40 and self.__s4 >= 40 and self.__s5 >= 40:
return True
else:
return False
def results(self):
print("Sno:\t", self.sno)
print("Sname:\t", self.sname)
print("S1:\t", self.__s1)
print("S2:\t", self.__s2)
print("S3:\t", self.__s3)
print("S4:\t", self.__s4)
print("S5:\t", self.__s5)
# it is a local variable
total = self.__sum()
print("Total marks:\t", total)
if (self.__isPass()):
print("Result: Pass")
else:
print("Result: Fail")
if __name__ == "__main__":
obj1 = Student(101, "Ranjith", 90, 100, 89, 99, 98)
obj1.results()
output:
Sno: 101
Sname: Ranjith
S1: 90
S2: 100
S3: 89
S4: 99
S5: 98
Total marks: 476
Result: Pass
30 For doubts about this document you can whatsapp me: Madhu.K(9912280626)
What Is encapsulation?
Example on encapsulation
class Student:
"in this class i am binding data(attribute) and
methods(functions) so it is called as encapsulation"
university = "JNTU"
def show(self):
print(f"Details of Student with id '{self.sno}'")
print("Sname:\t", self.sname)
print("Group:\t", self.group)
if __name__ == "__main__":
31 For doubts about this document you can whatsapp me: Madhu.K(9912280626)
What is encapsulation?
Process of binding data with methods is called encapsulation.
class One:
def __init__(self):
# __a, __b are called as private attributes or
instance variables
self.__a = 0
self.__b = 0
def getA(self):
return self.__a
def getB(self):
return self.__b
o1 = One()
# directly we can't access private variables outside the
class
# print(o1.__a)
# print(o1.__b)
What is a property?
A property is a private variable, which has setter and getter methods, like we did in above example
def getA(self):
return self.__a
def getB(self):
return self.__b
a = property(getA, setA)
b = property(getB, setB)
33 For doubts about this document you can whatsapp me: Madhu.K(9912280626)
o1 = One()
o1.a = 100 # o1.setA(100)
print(o1.a) # print(o1.getA())
o1.b = 200 # o1.setB(200)
print(o1.b) # print(o1.getB())
output:
100
200
class person:
def __init__(self, name="Guest"):
self.__name=name
def setname(self, name):
print("setname() called");
self.__name=name
def getname(self):
print("getname() called");
return self.__name
name=property(getname,setname);
p1=person();
p1.name="Jagadish";
print("p1.name:\t",p1.name);
Explanation:
In the above example, property(getname, setname) returns the property object and assigns it
to name. Thus, the name property hides the private instance attribute __name. The name property is
accessed directly, but internally it will invoke the getname() or setname() method, as shown below.
34 For doubts about this document you can whatsapp me: Madhu.K(9912280626)
def getA(self):
print("getting value of __a")
return self.__a
def delA(self):
print("__a is 'deleted' from object.......")
del self.__a
o1 = One()
o1.a = 100 # o1.setA(100)
print(o1.a)
del o1.a
print(o1.a)
outut:
setting value to __a is done..
setting value to __a is done..
getting value of __a
100
__a is 'deleted' from object.......
getting value of __a
Traceback (most recent call last):
File "c:\Users\hp\Documents\Python\NTSpecial\Programs\
Encapsulation2.py", line 24, in <module>
print(o1.a)
^^^^
File "c:\Users\hp\Documents\Python\NTSpecial\Programs\
Encapsulation2.py", line 11, in getA
return self.__a
^^^^^^^^
AttributeError: 'One' object has no attribute '_One__a'. Did
you mean: '__ne__'?
Decorators
• Decorators are very powerful and useful tool in Python since it allows programmers to
modify the behavior of function or class.
35 For doubts about this document you can whatsapp me: Madhu.K(9912280626)
• In Python, the function is a first-order object. It means that it can be passed as an argument to
another function.
• It is also possible to define a function inside another function. Such a function is called a
nested function.
• Moreover, a function can return another function.
@property Decorator
Example:
"""
How to use decorator @property?
1. We have to decorate @property to a getter function
2. gettter and setter function name must be same
3. we have to decorate setter function by using this below syntax
syntax: @<getterfunction name>.setter
"""
class One:
def __init__(self,a,b):
print("Parameterized constructor...")
self.__a=a
self.__b=b
@property
def a(self):
return self.__a
@a.setter
def a(self,a):
self.__a=a
o1=One(100,200)
print(o1.a)
o1.a=100000
print(o1.a)
class One:
def __init__(self):
self.__a=0
@a.setter
def x(self,a):
print("set function is invoked...")
self.__a=a
36 For doubts about this document you can whatsapp me: Madhu.K(9912280626)
o1=One()
o1.x=100
print(o1.x)
Polymorphism
Polymorphism means it has the ability to take more than one form. In python we can implement
polymorphism by using method overriding.
class Bird:
# parameterized constructor
def __init__(self, breed, name, color):
self.breed = breed
self.name = name
self.color = color
def makesNoise(self):
print(self.name, " Makes noise")
def fly(self):
print(self.name, "can fly")
class Sparrow(Bird):
# in the child class i am overriding makesNoise() method
def makesNoise(self):
print(self.name, " Chirps")
class Ostrich(Bird):
def fly(self):
print(self.name, " Can't Fly")
def makesNoise(self):
print(self.name, " is Booming")
def behavior(bird):
37 For doubts about this document you can whatsapp me: Madhu.K(9912280626)
bird.makesNoise()
bird.fly()
Hybrid inheritance
38 For doubts about this document you can whatsapp me: Madhu.K(9912280626)
Exception Handling
# logical error
def add():
a = 10
b = 2
c = a*b
print("Addition of 2 numbers:\t", c)
# run-time error
# the below code causes run-time error if b
value is zero
Output-2:
Addition of 2 numbers: 20
Enter an integer: 10
Enter another integer: 0
Traceback (most recent call last):
File "c:\Users\hp\Documents\Python\
NTSpecial\Programs\Errors.py", line 27, in
<module>
div(a, b)
File "c:\Users\hp\Documents\Python\
NTSpecial\Programs\Errors.py", line 19, in
div
r = a/b
~^~
ZeroDivisionError: division by zero
40 For doubts about this document you can whatsapp me: Madhu.K(9912280626)
Exception Handling is a mechanism used to handle runtime errors. If we handle runtimer errors the
program will not be terminated in middle of execution.
Exception can be said to be any abnormal condition in a program which causes termination in middle
of program execution.
Common Exceptions
• ZeroDivisionError: Occurs when a number is divided by zero.
• NameError: It occurs when a name is not found. It may be local or global.
• IndentationError: If incorrect indentation is given.
• IOError: It occurs when Input Output operation fails.
• EOFError: It occurs when end of the file is reached and yet operations are being performed.
41 For doubts about this document you can whatsapp me: Madhu.K(9912280626)
# after that it actually put that error
information in an object and throws that
object
# if that thrown object is not handled by
the programmer in program, then the program
will be terminated
"""
Note: the object which is thrown by the
PVM is called as an exception object.
"""
# in your prgram if you have statements,
that might cause run-time errors have to be
placed in try block to handle those runt time
errors
r = "Infinite"
try:
r = a/b # ZeroDivisionError is gonna
occur if b is zero
except:
print("Oh my god! run time error is
occured...")
print("Result")
print(f"{a}/{b}:\t{r}")
a = int(input("Enter an integer:\t"))
b = int(input("Enter another integer:\t"))
42 For doubts about this document you can whatsapp me: Madhu.K(9912280626)
div(a, b)
Else block:
1. Else block is executed if no except block is executed
2. Else block must be after except block before finally (if existed) block
Raise keyword:
1. The raise keyword is used to raise or generate an exception/error by the user/programmer
Finally block:
1. It is executed everytime when we run a program, whether we have handled an exception or
not, or occurred or not.
2. If you want to write both finally and else block, finally block must be the last one.
Syntax:
try:
malicious code
except Exception1:
execute code
except Exception2:
execute code
....
....
except ExceptionN:
execute code
else:
In case of no exception, execute the else block code.
43 For doubts about this document you can whatsapp me: Madhu.K(9912280626)