SlideShare a Scribd company logo
Unit – V Object Oriented Programming in Python
Object oriented Concepts: Creating class, Creating object
• Class- Classes are defined by the user. The class provides the
basic structure for an object. It consists of data members and
method members that are used by the instances(object) of the
class.
• Object- A unique instance of a data structure that is defined by
its class. An object comprises both data members and methods.
Class itself does nothing but real functionality is achieved through their
objects.
Creating Classes:
• Syntax :-
class ClassName:
#list of python class variables
# Python class constructor
#Python class method definitions
• In a class we can define variables, functions etc. While writing function in class we have to
pass atleast one argument that is called self parameter.
• The self parameter is a reference to the class itself and is used to access variables that
belongs to the class.
Example:
Example: Creating class
class student:
def display(self):
print("Hello Python")
In python programming self is a default variable that contains the memory address
of the instance of the current class.
Creating Objects-Objects can be used to access the attributes of the class
s1=student() #creating object of class
s1.display() #calling method of class using object
Instance variable and Class variable:
• Instance variable is defined in a method and its scope is only within the object
that defines it
• Class variable is defined in the class and can be used by all the instances of that
class.
• Instance variables are unique for each instance, while class variables are shared
by all instances.
Example: For instance and class variables
• class sample:
x=2 # x is class variable
def get(self,y): # y is instance variable
self.y=y
s1=sample()
s1.get(3)
print(s1.x," ",s1.y)
s2=sample()
S2.get(4)
print(s2.x," ",s2.y)
Example: Class with get and put method
• class car:
def get(self,color,style):
self.color=color
self.style=style
def put(self):
print(self.color)
print(self.style)
• c=car()
• c.get('Black','Red')
• c.put()
Method Overloading
• Method overloading is the ability to define the method with the same
name but with a different number of arguments and data types.
• Python does not support method overloading i.e it is not possible to
define more than one method with the same name in a class in python.
• This is because method arguments in python do not have a type.
Method Overloading
# To calculate area of rectangle
• def area(length,breadth):
calc=length*breadth
print(calc)
• # To calculate area of square
• def area(size):
calc=size*size
print(calc)
area(3)
area(4,5)
• Output9
Traceback (most recent call last):
File "D:python programstrial.py", line 10, in <module>
area(4,5)
TypeError: area() takes 1 positional argument but 2 were given
Data hiding
• Data hiding is a software development technique specifically used in object
oriented programming to hide internal object details(data members).
• Data hiding is also known as information hiding. An objects attributes may
or may not be visible outside the class definition
• In Python, you can achieve data hiding by using a double underscore prefix
(__) before an attribute or method name
• Any variable prefix
• with double underscore is called private variable which is accessible only
• with class where it is declared
• class counter:
• __secretcount=0 # private variable
• def count(self): # public method
• self.__secretcount+=1
• print("count= ",self.__secretcount) # accessible in the same class
• c1=counter()
• c1.count() # invoke method
• c1.count()
• print("Total count= ",c1.__secretcount) # cannot access private variable directly
Output:
• count= 1
• count= 2
• Traceback (most recent call last):
• File "D:python programsclass_method.py", line 9, in <module>
• print("Total count= ",c1.__secretcount) # cannot access private
variable
• directly
• AttributeError: 'counter' object has no attribute '__secretcount'
Data abstraction
• Data abstraction refers to providing only essential information about the data to
the outside world, hiding the background details of implementation.
• In short hiding internal details and showing functionality is known as abstraction.
• Access modifiers for variables and methods are:
• Public methods / variables- Accessible from anywhere inside the class, in the sub
class, in same script file as well as outside the script file.
• Private methods / variables- Accessible only in their own class. Starts with two
underscores.
Example: For access modifiers with data abstraction
• class student:
__a=10 #private variable
b=20 #public variable
def __private_method(self): #private method
print("Private method is called")
def public_method(self): #public method
print("public method is called")
print("a= ",self.__a) #can be accessible in same
class
s1=student()
# print("a= ",s1.__a) #generate error
print("b=",s1.b)
# s1.__private_method() #generate error
Output: b= 20
public method is called
a= 10
Encapsulation
• Encapsulation is a process to bind data and functions together into a
single unit i.e. class while abstraction is a process in which the data
inside the class is the hidden from outside world
Creating Constructor:
• Constructors are generally used for instantiating an object.
• The task of constructors is to initialize(assign values) to the data
members of the class when an object of class is created.
• In Python the __init__() method is called the constructor and is
always called when an object is created.
• Syntax of constructor declaration :
• def __init__(self):
# body of the constructor
Example: For creating constructor use_ _init_ _ method called
as constructor.
class student:
def __init__(self,rollno,name,age):
self.rollno=rollno
self.name=name
self.age=age
print("student object is created")
p1=student(11,"Ajay",20)
print("Roll No of student= ",p1.rollno)
print("Name No of student= ",p1.name)
print("Age No of student= ",p1.age)
Output:
student object is created
Roll No of student= 11
Name No of student= Ajay
Age No of student= 20
• Define a class rectangle using length and width.It has a method which
can compute area.
• Create a circle class and initialize it with radius. Make two methods
getarea and getcircumference inside this class
Types of Constructor:
• There are two types of constructor-
• Default constructor
• Parameterized constructor
Default constructor-
• The default constructor is simple constructor which does not accept any
arguments. Its definition has only one argument which is a reference to the
instance being constructed.
class student:
def __init__(self):
print("This is non parameterized constructor")
def show(self,name):
print("Hello",name)
s1=student()
s1.show("World")
Parameterized constructor-
• Constructor with parameters is known as parameterized constructor.
• The parameterized constructor take its first argument as a reference to the
instance being constructed known as self and the rest of the arguments are
provided by the programmer.
Example: For parameterized constructor
class student:
def __init__(self,name):
print("This is parameterized constructor")
self.name=name
def show(self):
print("Hello",self.name)
s1=student("World“)
s1.show()
Destructor:
• A class can define a special method called destructor with the help of _ _del_
_().
• It is invoked automatically when the instance (object) is about to be destroyed.
• It is mostly used to clean up non memory resources used by an instance(object).
Example: For Destructor
class student:
def __init__(self):
print("This is non parameterized constructor")
Example: For Destructor
class student:
def __init__(self):
print("This is non parameterized constructor")
def __del__(self):
print("Destructor called")
• s1=student()
• s2=student()
• del s1
Inheritance:
• The mechanism of designing and constructing classes from other classes is called
inheritance.
• Inheritance is the capability of one class to derive or inherit the properties from
some another class.
• Single Inheritance
• Multiple Inheritance
• Multilevel Inheritance
• Hierarchical Inheritance
Single Inheritance
• Single inheritance enables a derived class to inherit properties from a single
parent class
• Syntax:
Class A:
# Properties of class A
Class B(A):
# Class B inheriting property of class A
# more properties of class B
Example 1: Example of Inheritance without using constructor
class vehicle:
name="Maruti"
def display(self):
print("Name= ",self.name)
class category(vehicle):
price=400000
def disp_price(self):
print("price= ",self.price)
car1=category()
car1.display()
car1.disp_price()
Example 2: Example of Inheritance using constructor
class vehicle:
def __init__(self,name,price):
self.name=name
self.price=price
def display(self):
print("Name= ",self.name)
class category(vehicle):
def __init__(self,name,price):
vehicle.__init__(self,name,price) #pass data to base constructor
def disp_price(self):
print("price= ",self.price)
car1=category("Maruti",400000)
car1.display()
car1.disp_price()
Multilevel Inheritance:
• In multilevel inheritance, features of the base class and the derived class are
further inherited into the new derived class. This is similar to a relationship
representing a child and grandfather
• Syntax:
Class A:
# Properties of class A
Class B(A):
# Class B inheriting property of class A
# more properties of class B
Class C(B):
# Class C inheriting property of class B
# thus, Class C also inherits properties of class A
class c1:
def display1(self,a):
self.a=a
print("class c1 value“, self.a)
class c2(c1):
def display2(self,b):
self.b=b
print("class c2 value“, self.b)
class c3(c2)
def display3(self):
self.c=c
print("class c3 value“, self.c)
s1=c3()
s1.display3(10)
s1.display2(20)
s1.display1(30)
Multiple Inheritance:
• When a class can be derived from more than one base classes this type of
inheritance is called multiple inheritance. In multiple inheritance, all the features of
the base classes are inherited into the derived class.
Syntax:
Class A:
# variable of class A
# functions of class A
Class B:
# variable of class B
# functions of class B
Class C(A,B):
# Class C inheriting property of both class A and B
Example: Python program to demonstrate multiple inheritance
class Father:
def display1(self):
print("Father")
class Mother:
def display2(self):
print("Mother")
class Son(Father,Mother):
def display3(self):
print("Son")
s1 = Son()
s1.display3()
s1.display2()
s1.display1()
Hierarchical Inheritance:
• When more than one derived classes are created from a single base this type of
inheritence is called hierarchical inheritance. In this program, we have a parent
(base) class and two child (derived) classes.
Example : Python program to demonstrate Hierarchical inheritance
class Parent:
def func1(self):
print("This function is in parent class.")
class Child1(Parent):
def func2(self):
print("This function is in child 1.")
class Child2(Parent):
def func3(self):
print("This function is in child 2.")
object1 = Child1()
object1.func1()
object1.func2()
Ad

More Related Content

Similar to Unit – V Object Oriented Programming in Python.pptx (20)

C++ Presen. tation.pptx
C++ Presen.                   tation.pptxC++ Presen.                   tation.pptx
C++ Presen. tation.pptx
mohitsinha7739289047
 
Python programming : Classes objects
Python programming : Classes objectsPython programming : Classes objects
Python programming : Classes objects
Emertxe Information Technologies Pvt Ltd
 
UNIT - IIInew.pptx
UNIT - IIInew.pptxUNIT - IIInew.pptx
UNIT - IIInew.pptx
akila m
 
Classes & Objects _
Classes & Objects                             _Classes & Objects                             _
Classes & Objects _
swati463221
 
C# classes objects
C#  classes objectsC#  classes objects
C# classes objects
Dr.Neeraj Kumar Pandey
 
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdfPython Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
SudhanshiBakre1
 
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdfPython Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
SudhanshiBakre1
 
Pythonclass
PythonclassPythonclass
Pythonclass
baabtra.com - No. 1 supplier of quality freshers
 
Java Classes fact general wireless-19*5.pptx
Java Classes fact general wireless-19*5.pptxJava Classes fact general wireless-19*5.pptx
Java Classes fact general wireless-19*5.pptx
IbrahimMerzayiee
 
introduction_OOP for the java courses [Autosaved].pptx
introduction_OOP for the java courses [Autosaved].pptxintroduction_OOP for the java courses [Autosaved].pptx
introduction_OOP for the java courses [Autosaved].pptx
DrShamimAlMamun
 
asic computer is an electronic device that can receive, store, process, and o...
asic computer is an electronic device that can receive, store, process, and o...asic computer is an electronic device that can receive, store, process, and o...
asic computer is an electronic device that can receive, store, process, and o...
vaishalisharma125399
 
C++ppt. Classs and object, class and object
C++ppt. Classs and object, class and objectC++ppt. Classs and object, class and object
C++ppt. Classs and object, class and object
secondakay
 
Introduction to Python - Part Three
Introduction to Python - Part ThreeIntroduction to Python - Part Three
Introduction to Python - Part Three
amiable_indian
 
Presentation 3rd
Presentation 3rdPresentation 3rd
Presentation 3rd
Connex
 
Introduce oop in python
Introduce oop in pythonIntroduce oop in python
Introduce oop in python
tuan vo
 
My Object Oriented.pptx
My Object Oriented.pptxMy Object Oriented.pptx
My Object Oriented.pptx
GopalNarayan7
 
constructors.pptx
constructors.pptxconstructors.pptx
constructors.pptx
Epsiba1
 
Core Java unit no. 1 object and class ppt
Core Java unit no. 1 object and class pptCore Java unit no. 1 object and class ppt
Core Java unit no. 1 object and class ppt
Mochi263119
 
Core Java unit no. 1 object and class ppt
Core Java unit no. 1 object and class pptCore Java unit no. 1 object and class ppt
Core Java unit no. 1 object and class ppt
Mochi263119
 
Introduction to java programming
Introduction to java programmingIntroduction to java programming
Introduction to java programming
shinyduela
 
UNIT - IIInew.pptx
UNIT - IIInew.pptxUNIT - IIInew.pptx
UNIT - IIInew.pptx
akila m
 
Classes & Objects _
Classes & Objects                             _Classes & Objects                             _
Classes & Objects _
swati463221
 
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdfPython Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
SudhanshiBakre1
 
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdfPython Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
SudhanshiBakre1
 
Java Classes fact general wireless-19*5.pptx
Java Classes fact general wireless-19*5.pptxJava Classes fact general wireless-19*5.pptx
Java Classes fact general wireless-19*5.pptx
IbrahimMerzayiee
 
introduction_OOP for the java courses [Autosaved].pptx
introduction_OOP for the java courses [Autosaved].pptxintroduction_OOP for the java courses [Autosaved].pptx
introduction_OOP for the java courses [Autosaved].pptx
DrShamimAlMamun
 
asic computer is an electronic device that can receive, store, process, and o...
asic computer is an electronic device that can receive, store, process, and o...asic computer is an electronic device that can receive, store, process, and o...
asic computer is an electronic device that can receive, store, process, and o...
vaishalisharma125399
 
C++ppt. Classs and object, class and object
C++ppt. Classs and object, class and objectC++ppt. Classs and object, class and object
C++ppt. Classs and object, class and object
secondakay
 
Introduction to Python - Part Three
Introduction to Python - Part ThreeIntroduction to Python - Part Three
Introduction to Python - Part Three
amiable_indian
 
Presentation 3rd
Presentation 3rdPresentation 3rd
Presentation 3rd
Connex
 
Introduce oop in python
Introduce oop in pythonIntroduce oop in python
Introduce oop in python
tuan vo
 
My Object Oriented.pptx
My Object Oriented.pptxMy Object Oriented.pptx
My Object Oriented.pptx
GopalNarayan7
 
constructors.pptx
constructors.pptxconstructors.pptx
constructors.pptx
Epsiba1
 
Core Java unit no. 1 object and class ppt
Core Java unit no. 1 object and class pptCore Java unit no. 1 object and class ppt
Core Java unit no. 1 object and class ppt
Mochi263119
 
Core Java unit no. 1 object and class ppt
Core Java unit no. 1 object and class pptCore Java unit no. 1 object and class ppt
Core Java unit no. 1 object and class ppt
Mochi263119
 
Introduction to java programming
Introduction to java programmingIntroduction to java programming
Introduction to java programming
shinyduela
 

Recently uploaded (20)

Cultivation Practice of Garlic in Nepal.pptx
Cultivation Practice of Garlic in Nepal.pptxCultivation Practice of Garlic in Nepal.pptx
Cultivation Practice of Garlic in Nepal.pptx
UmeshTimilsina1
 
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
Dr. Nasir Mustafa
 
2025 The Senior Landscape and SET plan preparations.pptx
2025 The Senior Landscape and SET plan preparations.pptx2025 The Senior Landscape and SET plan preparations.pptx
2025 The Senior Landscape and SET plan preparations.pptx
mansk2
 
How to Manage Amounts in Local Currency in Odoo 18 Purchase
How to Manage Amounts in Local Currency in Odoo 18 PurchaseHow to Manage Amounts in Local Currency in Odoo 18 Purchase
How to Manage Amounts in Local Currency in Odoo 18 Purchase
Celine George
 
Transform tomorrow: Master benefits analysis with Gen AI today webinar, 30 A...
Transform tomorrow: Master benefits analysis with Gen AI today webinar,  30 A...Transform tomorrow: Master benefits analysis with Gen AI today webinar,  30 A...
Transform tomorrow: Master benefits analysis with Gen AI today webinar, 30 A...
Association for Project Management
 
MEDICAL BIOLOGY MCQS BY. DR NASIR MUSTAFA
MEDICAL BIOLOGY MCQS  BY. DR NASIR MUSTAFAMEDICAL BIOLOGY MCQS  BY. DR NASIR MUSTAFA
MEDICAL BIOLOGY MCQS BY. DR NASIR MUSTAFA
Dr. Nasir Mustafa
 
Origin of Brahmi script: A breaking down of various theories
Origin of Brahmi script: A breaking down of various theoriesOrigin of Brahmi script: A breaking down of various theories
Origin of Brahmi script: A breaking down of various theories
PrachiSontakke5
 
*"The Segmented Blueprint: Unlocking Insect Body Architecture"*.pptx
*"The Segmented Blueprint: Unlocking Insect Body Architecture"*.pptx*"The Segmented Blueprint: Unlocking Insect Body Architecture"*.pptx
*"The Segmented Blueprint: Unlocking Insect Body Architecture"*.pptx
Arshad Shaikh
 
APGAR SCORE BY sweety Tamanna Mahapatra MSc Pediatric
APGAR SCORE  BY sweety Tamanna Mahapatra MSc PediatricAPGAR SCORE  BY sweety Tamanna Mahapatra MSc Pediatric
APGAR SCORE BY sweety Tamanna Mahapatra MSc Pediatric
SweetytamannaMohapat
 
The role of wall art in interior designing
The role of wall art in interior designingThe role of wall art in interior designing
The role of wall art in interior designing
meghaark2110
 
How to Configure Public Holidays & Mandatory Days in Odoo 18
How to Configure Public Holidays & Mandatory Days in Odoo 18How to Configure Public Holidays & Mandatory Days in Odoo 18
How to Configure Public Holidays & Mandatory Days in Odoo 18
Celine George
 
antiquity of writing in ancient India- literary & archaeological evidence
antiquity of writing in ancient India- literary & archaeological evidenceantiquity of writing in ancient India- literary & archaeological evidence
antiquity of writing in ancient India- literary & archaeological evidence
PrachiSontakke5
 
History Of The Monastery Of Mor Gabriel Philoxenos Yuhanon Dolabani
History Of The Monastery Of Mor Gabriel Philoxenos Yuhanon DolabaniHistory Of The Monastery Of Mor Gabriel Philoxenos Yuhanon Dolabani
History Of The Monastery Of Mor Gabriel Philoxenos Yuhanon Dolabani
fruinkamel7m
 
Cultivation Practice of Turmeric in Nepal.pptx
Cultivation Practice of Turmeric in Nepal.pptxCultivation Practice of Turmeric in Nepal.pptx
Cultivation Practice of Turmeric in Nepal.pptx
UmeshTimilsina1
 
Overview Well-Being and Creative Careers
Overview Well-Being and Creative CareersOverview Well-Being and Creative Careers
Overview Well-Being and Creative Careers
University of Amsterdam
 
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptxU3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
Mayuri Chavan
 
How to Share Accounts Between Companies in Odoo 18
How to Share Accounts Between Companies in Odoo 18How to Share Accounts Between Companies in Odoo 18
How to Share Accounts Between Companies in Odoo 18
Celine George
 
Myopathies (muscle disorders) for undergraduate
Myopathies (muscle disorders) for undergraduateMyopathies (muscle disorders) for undergraduate
Myopathies (muscle disorders) for undergraduate
Mohamed Rizk Khodair
 
*"Sensing the World: Insect Sensory Systems"*
*"Sensing the World: Insect Sensory Systems"**"Sensing the World: Insect Sensory Systems"*
*"Sensing the World: Insect Sensory Systems"*
Arshad Shaikh
 
What is the Philosophy of Statistics? (and how I was drawn to it)
What is the Philosophy of Statistics? (and how I was drawn to it)What is the Philosophy of Statistics? (and how I was drawn to it)
What is the Philosophy of Statistics? (and how I was drawn to it)
jemille6
 
Cultivation Practice of Garlic in Nepal.pptx
Cultivation Practice of Garlic in Nepal.pptxCultivation Practice of Garlic in Nepal.pptx
Cultivation Practice of Garlic in Nepal.pptx
UmeshTimilsina1
 
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
Dr. Nasir Mustafa
 
2025 The Senior Landscape and SET plan preparations.pptx
2025 The Senior Landscape and SET plan preparations.pptx2025 The Senior Landscape and SET plan preparations.pptx
2025 The Senior Landscape and SET plan preparations.pptx
mansk2
 
How to Manage Amounts in Local Currency in Odoo 18 Purchase
How to Manage Amounts in Local Currency in Odoo 18 PurchaseHow to Manage Amounts in Local Currency in Odoo 18 Purchase
How to Manage Amounts in Local Currency in Odoo 18 Purchase
Celine George
 
Transform tomorrow: Master benefits analysis with Gen AI today webinar, 30 A...
Transform tomorrow: Master benefits analysis with Gen AI today webinar,  30 A...Transform tomorrow: Master benefits analysis with Gen AI today webinar,  30 A...
Transform tomorrow: Master benefits analysis with Gen AI today webinar, 30 A...
Association for Project Management
 
MEDICAL BIOLOGY MCQS BY. DR NASIR MUSTAFA
MEDICAL BIOLOGY MCQS  BY. DR NASIR MUSTAFAMEDICAL BIOLOGY MCQS  BY. DR NASIR MUSTAFA
MEDICAL BIOLOGY MCQS BY. DR NASIR MUSTAFA
Dr. Nasir Mustafa
 
Origin of Brahmi script: A breaking down of various theories
Origin of Brahmi script: A breaking down of various theoriesOrigin of Brahmi script: A breaking down of various theories
Origin of Brahmi script: A breaking down of various theories
PrachiSontakke5
 
*"The Segmented Blueprint: Unlocking Insect Body Architecture"*.pptx
*"The Segmented Blueprint: Unlocking Insect Body Architecture"*.pptx*"The Segmented Blueprint: Unlocking Insect Body Architecture"*.pptx
*"The Segmented Blueprint: Unlocking Insect Body Architecture"*.pptx
Arshad Shaikh
 
APGAR SCORE BY sweety Tamanna Mahapatra MSc Pediatric
APGAR SCORE  BY sweety Tamanna Mahapatra MSc PediatricAPGAR SCORE  BY sweety Tamanna Mahapatra MSc Pediatric
APGAR SCORE BY sweety Tamanna Mahapatra MSc Pediatric
SweetytamannaMohapat
 
The role of wall art in interior designing
The role of wall art in interior designingThe role of wall art in interior designing
The role of wall art in interior designing
meghaark2110
 
How to Configure Public Holidays & Mandatory Days in Odoo 18
How to Configure Public Holidays & Mandatory Days in Odoo 18How to Configure Public Holidays & Mandatory Days in Odoo 18
How to Configure Public Holidays & Mandatory Days in Odoo 18
Celine George
 
antiquity of writing in ancient India- literary & archaeological evidence
antiquity of writing in ancient India- literary & archaeological evidenceantiquity of writing in ancient India- literary & archaeological evidence
antiquity of writing in ancient India- literary & archaeological evidence
PrachiSontakke5
 
History Of The Monastery Of Mor Gabriel Philoxenos Yuhanon Dolabani
History Of The Monastery Of Mor Gabriel Philoxenos Yuhanon DolabaniHistory Of The Monastery Of Mor Gabriel Philoxenos Yuhanon Dolabani
History Of The Monastery Of Mor Gabriel Philoxenos Yuhanon Dolabani
fruinkamel7m
 
Cultivation Practice of Turmeric in Nepal.pptx
Cultivation Practice of Turmeric in Nepal.pptxCultivation Practice of Turmeric in Nepal.pptx
Cultivation Practice of Turmeric in Nepal.pptx
UmeshTimilsina1
 
Overview Well-Being and Creative Careers
Overview Well-Being and Creative CareersOverview Well-Being and Creative Careers
Overview Well-Being and Creative Careers
University of Amsterdam
 
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptxU3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
Mayuri Chavan
 
How to Share Accounts Between Companies in Odoo 18
How to Share Accounts Between Companies in Odoo 18How to Share Accounts Between Companies in Odoo 18
How to Share Accounts Between Companies in Odoo 18
Celine George
 
Myopathies (muscle disorders) for undergraduate
Myopathies (muscle disorders) for undergraduateMyopathies (muscle disorders) for undergraduate
Myopathies (muscle disorders) for undergraduate
Mohamed Rizk Khodair
 
*"Sensing the World: Insect Sensory Systems"*
*"Sensing the World: Insect Sensory Systems"**"Sensing the World: Insect Sensory Systems"*
*"Sensing the World: Insect Sensory Systems"*
Arshad Shaikh
 
What is the Philosophy of Statistics? (and how I was drawn to it)
What is the Philosophy of Statistics? (and how I was drawn to it)What is the Philosophy of Statistics? (and how I was drawn to it)
What is the Philosophy of Statistics? (and how I was drawn to it)
jemille6
 
Ad

Unit – V Object Oriented Programming in Python.pptx

  • 1. Unit – V Object Oriented Programming in Python
  • 2. Object oriented Concepts: Creating class, Creating object • Class- Classes are defined by the user. The class provides the basic structure for an object. It consists of data members and method members that are used by the instances(object) of the class. • Object- A unique instance of a data structure that is defined by its class. An object comprises both data members and methods. Class itself does nothing but real functionality is achieved through their objects.
  • 3. Creating Classes: • Syntax :- class ClassName: #list of python class variables # Python class constructor #Python class method definitions • In a class we can define variables, functions etc. While writing function in class we have to pass atleast one argument that is called self parameter. • The self parameter is a reference to the class itself and is used to access variables that belongs to the class.
  • 4. Example: Example: Creating class class student: def display(self): print("Hello Python") In python programming self is a default variable that contains the memory address of the instance of the current class. Creating Objects-Objects can be used to access the attributes of the class s1=student() #creating object of class s1.display() #calling method of class using object
  • 5. Instance variable and Class variable: • Instance variable is defined in a method and its scope is only within the object that defines it • Class variable is defined in the class and can be used by all the instances of that class. • Instance variables are unique for each instance, while class variables are shared by all instances.
  • 6. Example: For instance and class variables • class sample: x=2 # x is class variable def get(self,y): # y is instance variable self.y=y s1=sample() s1.get(3) print(s1.x," ",s1.y) s2=sample() S2.get(4) print(s2.x," ",s2.y)
  • 7. Example: Class with get and put method • class car: def get(self,color,style): self.color=color self.style=style def put(self): print(self.color) print(self.style) • c=car() • c.get('Black','Red') • c.put()
  • 8. Method Overloading • Method overloading is the ability to define the method with the same name but with a different number of arguments and data types. • Python does not support method overloading i.e it is not possible to define more than one method with the same name in a class in python. • This is because method arguments in python do not have a type.
  • 9. Method Overloading # To calculate area of rectangle • def area(length,breadth): calc=length*breadth print(calc) • # To calculate area of square • def area(size): calc=size*size print(calc) area(3) area(4,5)
  • 10. • Output9 Traceback (most recent call last): File "D:python programstrial.py", line 10, in <module> area(4,5) TypeError: area() takes 1 positional argument but 2 were given
  • 11. Data hiding • Data hiding is a software development technique specifically used in object oriented programming to hide internal object details(data members). • Data hiding is also known as information hiding. An objects attributes may or may not be visible outside the class definition • In Python, you can achieve data hiding by using a double underscore prefix (__) before an attribute or method name • Any variable prefix • with double underscore is called private variable which is accessible only • with class where it is declared
  • 12. • class counter: • __secretcount=0 # private variable • def count(self): # public method • self.__secretcount+=1 • print("count= ",self.__secretcount) # accessible in the same class • c1=counter() • c1.count() # invoke method • c1.count() • print("Total count= ",c1.__secretcount) # cannot access private variable directly
  • 13. Output: • count= 1 • count= 2 • Traceback (most recent call last): • File "D:python programsclass_method.py", line 9, in <module> • print("Total count= ",c1.__secretcount) # cannot access private variable • directly • AttributeError: 'counter' object has no attribute '__secretcount'
  • 14. Data abstraction • Data abstraction refers to providing only essential information about the data to the outside world, hiding the background details of implementation. • In short hiding internal details and showing functionality is known as abstraction. • Access modifiers for variables and methods are: • Public methods / variables- Accessible from anywhere inside the class, in the sub class, in same script file as well as outside the script file. • Private methods / variables- Accessible only in their own class. Starts with two underscores.
  • 15. Example: For access modifiers with data abstraction • class student: __a=10 #private variable b=20 #public variable def __private_method(self): #private method print("Private method is called") def public_method(self): #public method print("public method is called") print("a= ",self.__a) #can be accessible in same class s1=student() # print("a= ",s1.__a) #generate error print("b=",s1.b) # s1.__private_method() #generate error Output: b= 20 public method is called a= 10
  • 16. Encapsulation • Encapsulation is a process to bind data and functions together into a single unit i.e. class while abstraction is a process in which the data inside the class is the hidden from outside world
  • 17. Creating Constructor: • Constructors are generally used for instantiating an object. • The task of constructors is to initialize(assign values) to the data members of the class when an object of class is created. • In Python the __init__() method is called the constructor and is always called when an object is created. • Syntax of constructor declaration : • def __init__(self): # body of the constructor
  • 18. Example: For creating constructor use_ _init_ _ method called as constructor. class student: def __init__(self,rollno,name,age): self.rollno=rollno self.name=name self.age=age print("student object is created") p1=student(11,"Ajay",20) print("Roll No of student= ",p1.rollno) print("Name No of student= ",p1.name) print("Age No of student= ",p1.age) Output: student object is created Roll No of student= 11 Name No of student= Ajay Age No of student= 20
  • 19. • Define a class rectangle using length and width.It has a method which can compute area. • Create a circle class and initialize it with radius. Make two methods getarea and getcircumference inside this class
  • 20. Types of Constructor: • There are two types of constructor- • Default constructor • Parameterized constructor
  • 21. Default constructor- • The default constructor is simple constructor which does not accept any arguments. Its definition has only one argument which is a reference to the instance being constructed. class student: def __init__(self): print("This is non parameterized constructor") def show(self,name): print("Hello",name) s1=student() s1.show("World")
  • 22. Parameterized constructor- • Constructor with parameters is known as parameterized constructor. • The parameterized constructor take its first argument as a reference to the instance being constructed known as self and the rest of the arguments are provided by the programmer.
  • 23. Example: For parameterized constructor class student: def __init__(self,name): print("This is parameterized constructor") self.name=name def show(self): print("Hello",self.name) s1=student("World“) s1.show()
  • 24. Destructor: • A class can define a special method called destructor with the help of _ _del_ _(). • It is invoked automatically when the instance (object) is about to be destroyed. • It is mostly used to clean up non memory resources used by an instance(object). Example: For Destructor class student: def __init__(self): print("This is non parameterized constructor")
  • 25. Example: For Destructor class student: def __init__(self): print("This is non parameterized constructor") def __del__(self): print("Destructor called") • s1=student() • s2=student() • del s1
  • 26. Inheritance: • The mechanism of designing and constructing classes from other classes is called inheritance. • Inheritance is the capability of one class to derive or inherit the properties from some another class. • Single Inheritance • Multiple Inheritance • Multilevel Inheritance • Hierarchical Inheritance
  • 27. Single Inheritance • Single inheritance enables a derived class to inherit properties from a single parent class • Syntax: Class A: # Properties of class A Class B(A): # Class B inheriting property of class A # more properties of class B
  • 28. Example 1: Example of Inheritance without using constructor class vehicle: name="Maruti" def display(self): print("Name= ",self.name) class category(vehicle): price=400000 def disp_price(self): print("price= ",self.price) car1=category() car1.display() car1.disp_price()
  • 29. Example 2: Example of Inheritance using constructor class vehicle: def __init__(self,name,price): self.name=name self.price=price def display(self): print("Name= ",self.name) class category(vehicle): def __init__(self,name,price): vehicle.__init__(self,name,price) #pass data to base constructor def disp_price(self): print("price= ",self.price) car1=category("Maruti",400000) car1.display() car1.disp_price()
  • 30. Multilevel Inheritance: • In multilevel inheritance, features of the base class and the derived class are further inherited into the new derived class. This is similar to a relationship representing a child and grandfather • Syntax: Class A: # Properties of class A Class B(A): # Class B inheriting property of class A # more properties of class B Class C(B): # Class C inheriting property of class B # thus, Class C also inherits properties of class A
  • 31. class c1: def display1(self,a): self.a=a print("class c1 value“, self.a) class c2(c1): def display2(self,b): self.b=b print("class c2 value“, self.b) class c3(c2) def display3(self): self.c=c print("class c3 value“, self.c) s1=c3() s1.display3(10) s1.display2(20) s1.display1(30)
  • 32. Multiple Inheritance: • When a class can be derived from more than one base classes this type of inheritance is called multiple inheritance. In multiple inheritance, all the features of the base classes are inherited into the derived class. Syntax: Class A: # variable of class A # functions of class A Class B: # variable of class B # functions of class B Class C(A,B): # Class C inheriting property of both class A and B
  • 33. Example: Python program to demonstrate multiple inheritance class Father: def display1(self): print("Father") class Mother: def display2(self): print("Mother") class Son(Father,Mother): def display3(self): print("Son") s1 = Son() s1.display3() s1.display2() s1.display1()
  • 34. Hierarchical Inheritance: • When more than one derived classes are created from a single base this type of inheritence is called hierarchical inheritance. In this program, we have a parent (base) class and two child (derived) classes.
  • 35. Example : Python program to demonstrate Hierarchical inheritance class Parent: def func1(self): print("This function is in parent class.") class Child1(Parent): def func2(self): print("This function is in child 1.") class Child2(Parent): def func3(self): print("This function is in child 2.") object1 = Child1() object1.func1() object1.func2()
  翻译: