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

Week-2 Day12 Oops

The document discusses object-oriented programming concepts in Python including classes, objects, and methods. It defines a class as a blueprint for objects and an object as an instance of a class. Key concepts covered include: - Classes define attributes and behaviors while objects are instances created from classes. - The __init__() method is called automatically when an object is instantiated and is used to initialize attributes. - Methods defined inside classes can access attributes of their object using the self parameter. - Multiple objects can be created from the same class, each with their own distinct state defined by attribute values.

Uploaded by

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

Week-2 Day12 Oops

The document discusses object-oriented programming concepts in Python including classes, objects, and methods. It defines a class as a blueprint for objects and an object as an instance of a class. Key concepts covered include: - Classes define attributes and behaviors while objects are instances created from classes. - The __init__() method is called automatically when an object is instantiated and is used to initialize attributes. - Methods defined inside classes can access attributes of their object using the self parameter. - Multiple objects can be created from the same class, each with their own distinct state defined by attribute values.

Uploaded by

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

Object Oriented Programming Concepts

1. Python is called as an object oriented programming language, because python supports


oop’s concepts.

OOP’S Concepts

1. Data abstraction & Encapsulation


2. Polymorphism
3. Inheritance

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?

1. A blue print for objects.


2. A class is a template or prototype of an object

In general What is an object?

1. A real world physically existed thing, is called as object


Examples:
1. House
2. Computer
3. Fan
4. Byke
5. Car
6. Dog
7. Etc...

How we can construct a house?

1. We need house plan to construct a house


Like below

What is an object?

If you have constructed by using that house plan it is called as object.

In general this is 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?

A class is called as blue print

What is an object in python or any programming language?

Allocating memory based on blue print is called as object creation.

How to create a class?

There is a keyword called “class” in python, by using it we can create a class.

Example on class and object


# a basic example on class
class HousePlan:
# write a special function with name __init__ with one parameter
# in that function define some variable/attributes by u sing that
parameter
def __init__(self):
self.hall = None
self.kitchen = None
self.prayerRoom = None
self.living_area = None

2 For doubts about this document you can whatsapp me: Madhu.K(9912280626)
self.garage = None

# i want to create an object


house_1 = HousePlan()
house_1.garage = "Cars"
house_1.kitchen = "Things To Cook"
house_1.hall = "Thigs to get relaxed"
house_1.living_area = "Things to take rest"

print("House_1 object content")


print("Garage:\t", house_1.garage)
print("Kitchen:\t", house_1.kitchen)
print("Hall:\t", house_1.hall)
print("Living Area:\t", house_1.living_area)

# because house_1 variable contains object address, it is called as object

Output:
House_1 object content
Garage: Cars
Kitchen: Things To Cook
Hall: Thigs to get relaxed
Living Area: Things to take rest

Image explanation for above program

What is object?

Object is nothing but instance of a class.

What is object state?

The data we have stored in an object is called as object state.

What is object instantiation?

Object creation

What is Object initialization?

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.

What is the difference between a function and a method?

If you write a function with in a class, it is called as a method.

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

# We can call show() method by using object


# self=byke_1 #self=1002
def show(self): # byke_1
print("Object state....")
print(self.bykeNo) # None
print(self.color) # None
print(self.model)
print(self.vendor)
print(self.type)

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

The below Image about object creation in Heap Memory

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?

Object is an instance of a class.

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)

# Constructor calling statement


# When you call the constructor, first an empty object will
be create and that object will be passes as a argument to
the constructor
e1 = Emp()
# calling setEmp method
e1.setEmp()
# Emp.setEmp(e1)
# if you call display method, by using class name you have
to pass object as a parameter to that method
Emp.display(e1)

Important points about methods written in a class and self argument


The self
1. Methods written in class must have an extra first parameter in the method definition. We do not
give a value for this parameter when we call the method, Python provides it.
2. If we have a method that takes no arguments, then we still have to have one argument.
3. When we call a method of this object as myobject.method(arg1), this is automatically converted
by Python into MyClass.method(myobject, arg1)

Example on methods written in class with parameters


class Emp:
#constructor
def __init__(self):
self.eno=None
self.ename=None
self.sal=None

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

Example on creating many objects for a single class


class Emp:
#constructor
#self=1002,eno=1,ename="Ranjith",sal=300000.00
#self=2002,eno=2,ename="Akshitha",sal=400000.00
#self=3002,eno=3,ename="Ranjith",sal=500000.00
def __init__(self,eno,ename,sal):
self.eno=eno
self.ename=ename
self.sal=sal

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)

What is Instance variables?

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

How many times the class will be loaded by the PVM?

Class will be loaded by PVM only once, that can be used any no.of times during program execution.

Instance method

1. It is a method which takes present object implicitly as a first argument


2. We can call instance methods by using object or by passing object
3. We write instance methods, to access or update object state

What is object state?

The data existed in an object

Static Variables Example


class One:
# static variable or class variables
s = 100
# self=2002
# a=3000
# b=4000

def __init__(self, a, b):


# a,b which are declared by using self are called as
attributes or instance variables
self.a = a
self.b = b

# it is called as instance method


def show(self):
print("s:\t", One.s)
print("Object state...................")
print("self.a:\t", self.a)
print("self.b:\t", self.b)

# this is constructor calling cum object creation statement


obj1 = One(1000, 2000)
obj2 = One(3000, 4000)

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

Another example on static variables


class One:
# i have defined static variable to count the no.of
objects we are gonna create
count = 0
minBal = 500.00

def __init__(self, a, b):


# a,b which are declared by using self are called as
attributes or instance variables
self.a = a
self.b = b
# i am incrementing static variable
One.count = One.count+1
self.count = One.count

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)

# this is constructor calling cum object creation statement


obj1 = One(1000, 2000)
obj2 = One(3000, 4000)
obj1.show()
obj2.show()

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

Re-using the code which is written in one class in another class.

What is base class?

1. It is a class which is being inherited by another class


2. Base class is also called as parent or super class

What is child class?

1. It is a class which inherits the members of Base class.


2. It is also called derived or sub class.

12 For doubts about this document you can whatsapp me: Madhu.K(9912280626)
Forms of inheritance

1. Single-level or simple inheritance


2. Multiple inheritance

What is simple inheritance?

If a child class inherits only one base class at a time it is called as simple or single level inheritance.

What is multiple inheritance?

If a single child class inherits, more than one base class at a time it is called as multiple inheritance.

A basic Example on single level inheritance


class Base:
# constructor
def __init__(self, a, b):
print("Base class constructor...")
self.a = a
self.b = b

# object method or instance method


def show(self):

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

# i am creating child class object


cobj = Child(100, 200)
cobj.show()

output:
Base class constructor...
Object state....
self.a: 100
self.b: 200

Can we write morethan one method with same name in a class?

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.

Example on inheritance overriding/replacing methods and adding attributes dynamically after


constructor invocation/execution.

class Base:
# constructor
def __init__(self, a, b):
print("Base class parameterized constructor...")
self.a = a
self.b = b

# this constructor overrides or replaces the above


constructor
# self=1002
def __init__(self):
print("Base class non parameterized
constructor....")

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

# i am creating child class object


# cobj = Child(100, 200) you will get error
cobj = Child()
# Child.__init__(cobj)
# i am adding new property/attribute to the empty object
cobj.a = 100 # actually PVM assigns 100 to the
attribute/property a, if it is existed, otherwise it creates
new attribute and assigns 100
cobj.b = 200

cobj.show()
# Child.show(cobj)

Output:
Base class non parameterized constructor....
Object state....
self.a: 100
self.b: 200

What is destructor and when it will be invoked?

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

What kind of statements we might write in a destructor?

1. File closing statements


2. Databse connection closing statements etc..

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?

In the destructor we can write code to close the file

What is a garbage collector?

1. Garbage Collector actually destroys the objects which are in out of scope

When we override a method in child class?

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

# the b1 object scope is throughout the present program


b1 = Bird("Indian Parrot", "Parrot", "Green")
# Bird.__init__(b1)
b1.makeNoise()
b1.fly()

# I have written fun1() function outside the class


def fun1():
b2 = Sparrow("Indian sparrow", "Sparrow", "Light brown")
b2.makeNoise()
b2.fly()

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

What is multi-level inheritance?

1. If a child class is inherited by another child class it is called as multi-level inheritance


2. It is also extended form of single-level inheritance

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)

# b1 contains only one attribute 'a' with value 10


b1 = Base(10)
# c1 contains two attribute 'a' and 'b' with values 100,200
c1 = Child(100, 200)
# sc1 contains three attribute 'a','b' and 'c' with values
1000,2000,3000
sc1 = SubChild(1000, 2000, 3000)
print("b1 object state..........")
b1.display()
print("c1 object state..........")
c1.display()
print("sc1 object state..........")
sc1.display()

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

Calling base class constructor in child class constructor


class Base:
# self=1002
# a=100
# b=200
def __init__(self, a, b):
print("Base class parameterized constructor...")
self.a = a
self.b = b

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

# show method is instance method


def show(this):
# super().show()
Base.show(this)
print("self.c:\t", this.c)
print("self.d:\t", this.d)

# how to create object


cobj = Child(100, 200, 300, 400)
cobj.show()
# Child.show(cobj)

What are the other methods we can write with in a class?

1. Static methods
2. Class methods

What is a static method?

1. It is a method which is decorated by @staticmethod decorator


2. Static method doesn’t take any implicit first argument
3. We can call the static method by using class name or object
4. Static methods can access static variables but not instance variables
5. To access and modify the static variables we write static methods

What is class method?

1. It is a method which is decorated by @classmethod decorator


2. It takes present class as an implicit first argument
3. Class method can access static methods
4. It can’t access instance variable because self is not available by-default
5. We can call class methods by using class name or by using class name without passing
present object as a first argument but as a first argument the class will be sent

Example on static and class methods


class One:

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

def __init__(self, a, b):


print("constructor........")
self.a = a
self.b = b

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

# i m calling static method by using class name


One.fun1()
One.fun2(100)

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

It is a method which returns preset objects

Example on factory method


class One:
# It is parameterized constructor

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

# can we call the class methods by using class name


o1 = One.factory(10, 20)
o2 = One.factory(100, 200)
o3 = One.factory(1000, 2000)
o1.display()
o2.display()
o3.display()

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

Example on multiple inheritance


class Base1:
def __init__(self):
self.a = 0
# It is instance method

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

class Child(Base2, Base1):


pass

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

Example-2 on multiple inheritance


class Base1:
def __init__(self, a):
print("Base-1 constructor")
self.a = a
# It is instance 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)

class Child(Base1, Base2):


def __init__(self, a, b, c):
print("Child 1 constructor")
Base1.__init__(self, a)
Base2.__init__(self, b, c)

c1 = Child(10, 20, 30)


c1.fun1()
c1.fun2()

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

1. What is data abstraction & encapsulation


2. What is polymorphism
3. Access modifiers/specifiers

What is data abstraction?

Process of hiding un-necessary details from the end user and providing necessary details is called as
data abstraction.

How to declare private attributes?

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)

Ex: self.__a Here __a is a private attribute


Ex: self.a Here a is a public attribute
Ex: self._a Here _a is a protected attribute(it won’t work)

Example on data abstraction using attributes


class One:
def __init__(self):
# Here __a,__b are private attributes
# __a and __b are accessible only with in the class
self.__a = 10
self.__b = 20
# Here c is public attributes
# c is accessble with in the class and also outside
the class
self.c = 30
# Here _d is protected attributes

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

# __fun1() is a private instance method


def __fun1(self):
pass

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

Example on data abstraction


class Student:
def __init__(self, sno, sname, s1, s2, s3, s4, s5):
self.sno = sno
self.sname = sname
self.__s1 = s1
self.__s2 = s2
self.__s3 = s3
self.__s4 = s4
self.__s5 = s5
# i don't want to allow other classes to access the
__sum() function

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?

Process of binding the data and methods into a single unit(class)

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 __init__(self, sno, sname, group):


self.sno = sno
self.sname = sname
self.group = group

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__":

s1 = Student(1, "Jairam", "cse")


s2 = Student(2, "Akshitha", "eee")
print(f"Students of {Student.university}
Univiersity...")
s1.show()
s2.show()
output:
Students of JNTU Univiersity...
Details of Student with id '1'
Sname: Jairam
Group: cse
Details of Student with id '2'
Sname: Akshitha
Group: eee

Properties with setter and getter methods

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

# I am able to assign a value to private variable


through a method, from outside the class
def setA(self, a):
self.__a = a

def setB(self, b):


self.__b = b

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)

# we can access private variables outside the class by using


methods
o1.setA(100)
o1.setB(200)
a = o1.getA()
b = o1.getB()
print("Object state.....")
print("a:\t", a)
print("b:\t", b)
32 For doubts about this document you can whatsapp me: Madhu.K(9912280626)
output:
Object state.....
a: 100
b: 200

What is a property?

A property is a private variable, which has setter and getter methods, like we did in above example

Python - property () function


• Traditional object-oriented languages like Java and C# use properties in a class to
encapsulate data.
• Property includes the getter and setter method to access encapsulated data.
• A class in Python can also include properties by using the property() function.

Encapsulation without using property() function


class One:
def __init__(self):
# __a, __b are called as private attributes or
instance variables
self.__a = 0
self.__b = 0

# I am able to assign a value to private variable


through a method, from outside the class
def setA(self, a):
self.__a = a

def setB(self, b):


self.__b = b

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

Using Property method

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.

Delete property using property() function


class One:
def __init__(self):
self.__a = 0

def setA(self, a):


print("setting value to __a is done..")
self.__a = a

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

a = property(getA, setA, delA)

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)

Another Example On Setter

class One:
def __init__(self):
self.__a=0

@property #it is a decorator


def a(self):
print("get function is invoked...")
return self.__a

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

# Sparrow is the Child class now

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

b1 = Bird("Indian Parrot", "Parrot", "Green")


b2 = Sparrow("Indian sparrow", "Sparrow", "Light brown")
b3 = Ostrich("Struthionidae", "Ostrich", "Black & White")
behavior(b1)
behavior(b2)
behavior(b3)
output:
Parrot Makes noise
Parrot can fly
Sparrow Chirps
Sparrow can fly
Ostrich is Booming
Ostrich Can't Fly

Hybrid inheritance

It is the combination 2 or more forms


Cobining 2 or more forms into a new form, it is called as hybrid inheritance

38 For doubts about this document you can whatsapp me: Madhu.K(9912280626)
Exception Handling

Errors are of 3 types


1. Compile time errors(syntax errors)
2. Runtime errors(getting errors while running program)
3. Logical Errors(wrong loigic)
Example on different types of errors

# in the below function we have many syntax


errors
# def add():
# a=10b=20
# c=a+b
# print("add...")

# 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

def div(a, b):


r = a/b
print("Result")
print(f"{a}/{b}:\t{r}")
39 For doubts about this document you can whatsapp me: Madhu.K(9912280626)
add()
a = int(input("Enter an integer:\t"))
b = int(input("Enter another integer:\t"))
div(a, b)
output-1:
Addition of 2 numbers: 20
Enter an integer: 10
Enter another integer: 2
Result
10/2: 5.0

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.

Note: In python we have the following keywords to handle exceptions(runtime errors)


1. try: by using try keyword, we actually write a block
2. except
3. raise
4. finally
5. else
Try block:
1. In try block we place the statements, they migh cause an error or errors.
2. After try block we have to write either except block or finally block, we can’t write elese
block after try block.
3. You can’t write a try block without having either except or finally block
Except block:
1. It is used to handle the exceptions or runtime errros which are occurred in a try block during
program executeion.
2. We can write an except block either after try or except block.
3. After last except block we can write else block if we want
Example on try and except block

def div(a, b):


# whenever runtime error occurs, the
python virtual machine,
# collects the error information like
why(what is the cause) it was occured, where
it was occured(at which line and method) and
what type of error it is and

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)

You might also like