SlideShare a Scribd company logo
1
Python
RTS tech
1
Object Oriented Programming
RTS tech
Object Oriented Programming concept
 Module
 Class
 Object
 Encapsulation
 Inheritance
 Abstraction
 Polymorphism
RTS tech
Application
• One application is made of multiple modules
• A Module is a file with .py extension.
• A module can define functions, classes and
variables.
RTS tech
Module
 Module is a file of .py extension
RTS tech
6
Student.py
Following is Student module which contains two methods add()
and update( )
o def add_student( rollno, Name ):
o print("Adding Student")
o print('Name', Name )
o print(‘Rollno', rollno )
o return
o def update_student(Name ):
o print("Updating Student")
o print('Name', Name )
o return
RTS tech
7
• You can import a module by import statement
in python program. We are importing
Student.py module in TestStudent.py file.
o import Student
• Now we can use module functions:
o Student.add_student(1,”Sonu”)
o Student.add_student(2,”Monu”)
TestStudent.py
RTS tech
from ... Import statement
 We can import specific functions from a module using
from ...import statement.
o from Student import add,update
o add(1,"Ram")
o update("Shyam")
 You can import all methods using * character
 from Student import *
RTS tech
Module search path
 When you import a module, python interpreter searches
module in different directories in the following sequences:
 The current directory.
 If module is not found then searches each directory specified
 in environment variable PYTHONPATH.
 If all fails then python checks the default path.
 You can set PYTHONPATH as per your app requirements
 set PYTHONPATH =c:pythonlibl;c:pythonlib2;
RTS tech
Objects: Real world Entities
 Object=Related attributes+ Related methods
RTS tech
Objects vs Class
Attributes
• Color
• Brand
• Price
• …
Method
• take_Selfie()
• Calling()
• Messaging()
RTS tech
Virtual Entity Actual Entity
Class
 It is a structure of an Object.
 Class contains related attributes and methods of an
Object.
 Class keyword is used to define a class.
 Class contains the complete details about an object.
 Ex.
 Home
 Pen
 Chair
RTS tech
Object
• When we create a class only description is created no
memory is allocated.
• We can create an variable of the class.
• Variable is known as object(instance).
• We can create multiple object of the class.
RTS tech
Define a class
 ‘class’ keyword is used to define the class.
 Class Mobile:
 ‘contains all details about mobile’
 The first line after the class name is a document String.
 Class Members:
 Attributes
 Methods
 Constructor
 Destructor
RTS tech
Mobile
 class Mobile:
 "contains mobile information“
 #class variables are shared by all instance
 object_count=0
 def __init__(self):#constructor
 self.color = "" #instance attribute
 self.brand=“”
 Mobile.object_count+=1
 def get_color(self): #instance Method
 return self.color
 def set_color(self,color):
 self.color = color
RTS tech
TestMobile.py
 Create Object(variable) of Mobile class.
 We can create multiple object of the class.
 m1=Mobile()
 m2=Mobile()
 m1.set_color("black")
 Print Value of the Mobile
 print("Count",Mobile.object_count)
 print("color: ",m1.get_color())
RTS tech
Built in Class Attributes
 __doc__: to get doc string of the class.
 __dict__: to get dictionary of the class members.
 __bases__: to get base classes tuple.
 __name__: to get class name.
 __module__: to get module name.
RTS tech
Class attributes
 print("Dictonary:",Mobile.__dict__)
 print("Name:",Mobile.__name__)
 print("Document string:",Mobile.__doc__)
 print("Module:",Mobile.__module__)
 print("Bases:",Mobile.__bases__)
RTS tech
Class(static) attributes
 Class attributes are declared within a class but outside
method.
 class Mobile:
 object_count=0
 It is shared by all instance of the class.
 Static variables got memory one time.
 We can access class variable by class name.
 Mobile.object_count+=1
RTS tech
Instance (non-static) Attributes
 Instance variables are define inside the constructor.
 def __init__(self):#constructor
 self.color =""
 self.brand=“”
 Instance variable get memory for each instance
separately.
 We can access instance variable with the instance name.
RTS tech
Constructor
 Constructor is defined by __init__(self) method.
 Each class has only one constructor method.
 Constructor is used to initialize the class and instance
variable.
 It is executed at the time of object creation(instantiation
process).
 self keyword represent current instance.
RTS tech
Methods in a class
 Method is used to write business logic.
 Method is define by def keyword.
 Instance method contains a self attribute to access
instance variable.
 Class method does not require self keyword.
 We can access class method with the help of class name
 class Mobile:
 def get_color(self):
 return self.color
 def set_color(self,color):
 self.color = color
RTS tech
__del__(self)
 Destructor function remove an object from the memory.
 __del__() method is used to create destructor in a class.
 When an object is not in use the destructor function is
automatically called.
 def __del__(self):
 name=self.__class__.__name__
 print("Object is Destroyed {}".format(name))
RTS tech
Object to string
 We can convert an object into string form.
 __str__(self) method is used to create an string function in
a class.
 When we print an object the address is printed
 <__main__.Mobile object at 0x000001EA4D8670D0>
 after creating __str__(self) method in a class , when we
print an object the object is automatically converted into
string representation.
RTS tech
Inheritance
 It is a concept of OOP language.
 It is use to define a class based on another class.
 One class is known as Base or super class and another class is
known as Derived or sub class.
 Here Person is a Base class and Programmer, Doctor are Derived
classes.
 By default Each class has Object as Base Class.
 Syntax: class Doctor(Person):
 pass
Person
Programmer Doctor
Person
RTS tech
Types of Inheritance
Class A
Class B Class C
Class B
Class A
Class C
Class B
Class A Class A
Class B Class C
1.Single Level 2.Multi Level 3.Multiple 4. Hierarchical
RTS tech
Mobile
:
+IMEI:int
-brand:String
-color:String
-price:int
+getBrand():String
+setBrand():
:
-keypad:boolean
-radio:Boolean
+playRadio()
:
-ScreenSize:int
-osType:String
+setScreenSize():
+getScreenSize():int
RTS tech
:
+IMEI:int
-brand:String
-color:String
-price:int
+getBrand():String
+setBrand():
Mobile class
 class Mobile:
 counts=0
 def __init__(self, name=None,color=None,im=0,price=0):
 self.__name = name
 self.__color = color
 self.__price = price
 self.__IMEI = im
 Mobile.counts+=1
 #setter and getter methods
 def get_color(self):
 return self.__color
 def set_color(self, color):
 self.__color = color
RTS tech
BasicPhone class
 from mobile import Mobile
 class BasicPhone(Mobile):
 def __init__(self):
 self.__keypad=“”

def get_keypad(self):
 return self.__keypad
 def set_keypad(self,keypad):
 self.__keypad =keypad
 def tuneRadio(self):
 return "Tunning radio"
RTS tech
Create child class Instance
 from basicPhone import BasicPhone
 phone = BasicPhone()
 phone.setColor("Black")
 phone.setBrandName("Nokia")
 phone.setPrice(2000)
 phone.setKeypad(True)

print("--------Phone Info-------------")
 print("Color ={}".format(phone.getColor()))
 print("BrandName ={}".format(phone.getbrand()))
 print("Price ={}".format(phone.getPrice()))
 print("Radio {}".format(phone.tuneRadio()))
 print("Keypad:{}".format(phone.get_keypad()))
RTS tech
How to call Parent Class Constructor?
 from mobile import Mobile
 class SmartPhone(Mobile):
 def __init__(self,n,c,i,p,screen_size):
 self.__screen_size=screen_size
 # super(SmartPhone,self).__init__(n,c,i,p
 #OR
 super().__init__(n,c,i,p)
 def get_ScreenSize(self):
 return self.__screen_size
 def set_ScreenSize(self,screen_size):
 self.__screen_size = screen_size
RTS tech
Parent class constructor
 from smartPhone import SmartPhone
 sp=SmartPhone("REalMe","Black",12345671,20000,20)
 print("Price {}".format(sp.get_price()))
 print("Color {}".format(sp.get_color()))
 print("IMEI No {}".format(sp.get_IMEI()))
 print("Screen Size {}".format(sp.get_ScreenSize()))
RTS tech
Polymorphism
 Having many Forms.
RTS tech
Types of polymorphism
 Runtime
 Method Overriding
 Compile time
 Method Overloading
RTS tech
Method Overriding
RTS tech
:
-keypad:boolean
-radio:Boolean
+answerCall()
:
-ScreenSize:int
-osType:String
+answerCall()
:
+IMEI:int
-brand:String
-color:String
-price:int
+getBrand():String
+setBrand():
+answerCall()
Method Overriding(cont.)
 Sub class can override the Super class Method.
 class Mobile:
 def answer(self):
 print("Answer the call")
 class BasicPhone:
 def answer(self):
 print(“Press the key to answer the call")
 class SmartPhone:
 def answer(self):
 print(“Swipe right to answer the call")
RTS tech
Abstraction
RTS tech
Abstract class
 Abstract class contains abstract method.
 Abstract method has only method declaration no method
definition
 Different mobile phone has different implementation for
answerCall() method.
 We can not create instance of abstract class.
 Child class will provide implementation to the abstract
method.
RTS tech
Implementation
 from abc import ABC,abstractmethod
 class Mobile(ABC):
 @abstractmethod
 def answerCall(self):
 pass
 class BasicPhone:
 def answer(self):
 print(“Press the key to answer the call")
 class SmartPhone:
 def answer(self):
 print(“Swipe right to answer the call")
RTS tech
Disclaimer
 This is an educational presentation to enhance the skill of
computer science students.
 This presentation is available for free to computer science
students.
 Some internet images from different URLs are used in this
presentation to simplify technical examples and correlate
examples with the real world.
 We are grateful to owners of these URLs and pictures.
Thank You!
RTS Tech.
:rtstech30@gmail.com
:+91 8818887087

More Related Content

What's hot

Object-oriented Programming-with C#
Object-oriented Programming-with C#Object-oriented Programming-with C#
Object-oriented Programming-with C#
Doncho Minkov
 
Responsive Web Design with HTML5 and CSS3
Responsive Web Design with HTML5 and CSS3Responsive Web Design with HTML5 and CSS3
Responsive Web Design with HTML5 and CSS3
Kannika Kong
 
OOP-Advanced Programming with c++
OOP-Advanced Programming with c++OOP-Advanced Programming with c++
OOP-Advanced Programming with c++
Mohamed Essam
 

What's hot (20)

What is Dictionary In Python? Python Dictionary Tutorial | Edureka
What is Dictionary In Python? Python Dictionary Tutorial | EdurekaWhat is Dictionary In Python? Python Dictionary Tutorial | Edureka
What is Dictionary In Python? Python Dictionary Tutorial | Edureka
 
C# basics
 C# basics C# basics
C# basics
 
Introduction To C#
Introduction To C#Introduction To C#
Introduction To C#
 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteChapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
 
JavaScript - Chapter 12 - Document Object Model
  JavaScript - Chapter 12 - Document Object Model  JavaScript - Chapter 12 - Document Object Model
JavaScript - Chapter 12 - Document Object Model
 
Java script errors &amp; exceptions handling
Java script  errors &amp; exceptions handlingJava script  errors &amp; exceptions handling
Java script errors &amp; exceptions handling
 
Asp.net state management
Asp.net state managementAsp.net state management
Asp.net state management
 
Object-oriented Programming-with C#
Object-oriented Programming-with C#Object-oriented Programming-with C#
Object-oriented Programming-with C#
 
Class, object and inheritance in python
Class, object and inheritance in pythonClass, object and inheritance in python
Class, object and inheritance in python
 
PYTHON - TKINTER - GUI - PART 1.ppt
PYTHON - TKINTER - GUI - PART 1.pptPYTHON - TKINTER - GUI - PART 1.ppt
PYTHON - TKINTER - GUI - PART 1.ppt
 
Event In JavaScript
Event In JavaScriptEvent In JavaScript
Event In JavaScript
 
VB net lab.pdf
VB net lab.pdfVB net lab.pdf
VB net lab.pdf
 
Java script array
Java script arrayJava script array
Java script array
 
Responsive Web Design with HTML5 and CSS3
Responsive Web Design with HTML5 and CSS3Responsive Web Design with HTML5 and CSS3
Responsive Web Design with HTML5 and CSS3
 
Object oriented programming in python
Object oriented programming in pythonObject oriented programming in python
Object oriented programming in python
 
Android Navigation Component
Android Navigation ComponentAndroid Navigation Component
Android Navigation Component
 
OOP-Advanced Programming with c++
OOP-Advanced Programming with c++OOP-Advanced Programming with c++
OOP-Advanced Programming with c++
 
Angular - Chapter 4 - Data and Event Handling
 Angular - Chapter 4 - Data and Event Handling Angular - Chapter 4 - Data and Event Handling
Angular - Chapter 4 - Data and Event Handling
 
Python programming : Inheritance and polymorphism
Python programming : Inheritance and polymorphismPython programming : Inheritance and polymorphism
Python programming : Inheritance and polymorphism
 
Python oop third class
Python oop   third classPython oop   third class
Python oop third class
 

Similar to Python-oop

Sample UML Diagram – Employee ClassEmployee- count int- .docx
Sample UML Diagram – Employee ClassEmployee- count  int- .docxSample UML Diagram – Employee ClassEmployee- count  int- .docx
Sample UML Diagram – Employee ClassEmployee- count int- .docx
jeffsrosalyn
 
Presentation 4th
Presentation 4thPresentation 4th
Presentation 4th
Connex
 
03 oo with-c-sharp
03 oo with-c-sharp03 oo with-c-sharp
03 oo with-c-sharp
Naved khan
 
classes object fgfhdfgfdgfgfgfgfdoop.pptx
classes object  fgfhdfgfdgfgfgfgfdoop.pptxclasses object  fgfhdfgfdgfgfgfgfdoop.pptx
classes object fgfhdfgfdgfgfgfgfdoop.pptx
arjun431527
 
I assignmnt(oops)
I assignmnt(oops)I assignmnt(oops)
I assignmnt(oops)
Jay Patel
 

Similar to Python-oop (20)

Objective c
Objective cObjective c
Objective c
 
Sample UML Diagram – Employee ClassEmployee- count int- .docx
Sample UML Diagram – Employee ClassEmployee- count  int- .docxSample UML Diagram – Employee ClassEmployee- count  int- .docx
Sample UML Diagram – Employee ClassEmployee- count int- .docx
 
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
 
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
 
C#2
C#2C#2
C#2
 
CPP Homework Help
CPP Homework HelpCPP Homework Help
CPP Homework Help
 
Object oriented approach in python programming
Object oriented approach in python programmingObject oriented approach in python programming
Object oriented approach in python programming
 
Python_Unit_2 OOPS.pptx
Python_Unit_2  OOPS.pptxPython_Unit_2  OOPS.pptx
Python_Unit_2 OOPS.pptx
 
OOC MODULE1.pptx
OOC MODULE1.pptxOOC MODULE1.pptx
OOC MODULE1.pptx
 
Presentation 4th
Presentation 4thPresentation 4th
Presentation 4th
 
03 oo with-c-sharp
03 oo with-c-sharp03 oo with-c-sharp
03 oo with-c-sharp
 
Unit - 3.pptx
Unit - 3.pptxUnit - 3.pptx
Unit - 3.pptx
 
Introduction to c_plus_plus (6)
Introduction to c_plus_plus (6)Introduction to c_plus_plus (6)
Introduction to c_plus_plus (6)
 
Introduction to c_plus_plus
Introduction to c_plus_plusIntroduction to c_plus_plus
Introduction to c_plus_plus
 
classes object fgfhdfgfdgfgfgfgfdoop.pptx
classes object  fgfhdfgfdgfgfgfgfdoop.pptxclasses object  fgfhdfgfdgfgfgfgfdoop.pptx
classes object fgfhdfgfdgfgfgfgfdoop.pptx
 
Object Oriented Code RE with HexraysCodeXplorer
Object Oriented Code RE with HexraysCodeXplorerObject Oriented Code RE with HexraysCodeXplorer
Object Oriented Code RE with HexraysCodeXplorer
 
I assignmnt(oops)
I assignmnt(oops)I assignmnt(oops)
I assignmnt(oops)
 
201005 accelerometer and core Location
201005 accelerometer and core Location201005 accelerometer and core Location
201005 accelerometer and core Location
 
Getting Started - Console Program and Problem Solving
Getting Started - Console Program and Problem SolvingGetting Started - Console Program and Problem Solving
Getting Started - Console Program and Problem Solving
 
SPF Getting Started - Console Program
SPF Getting Started - Console ProgramSPF Getting Started - Console Program
SPF Getting Started - Console Program
 

Recently uploaded

Standard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - NeometrixStandard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - Neometrix
Neometrix_Engineering_Pvt_Ltd
 
Hall booking system project report .pdf
Hall booking system project report  .pdfHall booking system project report  .pdf
Hall booking system project report .pdf
Kamal Acharya
 
ONLINE VEHICLE RENTAL SYSTEM PROJECT REPORT.pdf
ONLINE VEHICLE RENTAL SYSTEM PROJECT REPORT.pdfONLINE VEHICLE RENTAL SYSTEM PROJECT REPORT.pdf
ONLINE VEHICLE RENTAL SYSTEM PROJECT REPORT.pdf
Kamal Acharya
 
Online blood donation management system project.pdf
Online blood donation management system project.pdfOnline blood donation management system project.pdf
Online blood donation management system project.pdf
Kamal Acharya
 

Recently uploaded (20)

KIT-601 Lecture Notes-UNIT-4.pdf Frequent Itemsets and Clustering
KIT-601 Lecture Notes-UNIT-4.pdf Frequent Itemsets and ClusteringKIT-601 Lecture Notes-UNIT-4.pdf Frequent Itemsets and Clustering
KIT-601 Lecture Notes-UNIT-4.pdf Frequent Itemsets and Clustering
 
The Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdfThe Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdf
 
ENERGY STORAGE DEVICES INTRODUCTION UNIT-I
ENERGY STORAGE DEVICES  INTRODUCTION UNIT-IENERGY STORAGE DEVICES  INTRODUCTION UNIT-I
ENERGY STORAGE DEVICES INTRODUCTION UNIT-I
 
Standard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - NeometrixStandard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - Neometrix
 
ASME IX(9) 2007 Full Version .pdf
ASME IX(9)  2007 Full Version       .pdfASME IX(9)  2007 Full Version       .pdf
ASME IX(9) 2007 Full Version .pdf
 
Furniture showroom management system project.pdf
Furniture showroom management system project.pdfFurniture showroom management system project.pdf
Furniture showroom management system project.pdf
 
IT-601 Lecture Notes-UNIT-2.pdf Data Analysis
IT-601 Lecture Notes-UNIT-2.pdf Data AnalysisIT-601 Lecture Notes-UNIT-2.pdf Data Analysis
IT-601 Lecture Notes-UNIT-2.pdf Data Analysis
 
A CASE STUDY ON ONLINE TICKET BOOKING SYSTEM PROJECT.pdf
A CASE STUDY ON ONLINE TICKET BOOKING SYSTEM PROJECT.pdfA CASE STUDY ON ONLINE TICKET BOOKING SYSTEM PROJECT.pdf
A CASE STUDY ON ONLINE TICKET BOOKING SYSTEM PROJECT.pdf
 
Hall booking system project report .pdf
Hall booking system project report  .pdfHall booking system project report  .pdf
Hall booking system project report .pdf
 
Scaling in conventional MOSFET for constant electric field and constant voltage
Scaling in conventional MOSFET for constant electric field and constant voltageScaling in conventional MOSFET for constant electric field and constant voltage
Scaling in conventional MOSFET for constant electric field and constant voltage
 
ONLINE VEHICLE RENTAL SYSTEM PROJECT REPORT.pdf
ONLINE VEHICLE RENTAL SYSTEM PROJECT REPORT.pdfONLINE VEHICLE RENTAL SYSTEM PROJECT REPORT.pdf
ONLINE VEHICLE RENTAL SYSTEM PROJECT REPORT.pdf
 
Explosives Industry manufacturing process.pdf
Explosives Industry manufacturing process.pdfExplosives Industry manufacturing process.pdf
Explosives Industry manufacturing process.pdf
 
Quality defects in TMT Bars, Possible causes and Potential Solutions.
Quality defects in TMT Bars, Possible causes and Potential Solutions.Quality defects in TMT Bars, Possible causes and Potential Solutions.
Quality defects in TMT Bars, Possible causes and Potential Solutions.
 
Halogenation process of chemical process industries
Halogenation process of chemical process industriesHalogenation process of chemical process industries
Halogenation process of chemical process industries
 
Construction method of steel structure space frame .pptx
Construction method of steel structure space frame .pptxConstruction method of steel structure space frame .pptx
Construction method of steel structure space frame .pptx
 
HYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generationHYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generation
 
Online blood donation management system project.pdf
Online blood donation management system project.pdfOnline blood donation management system project.pdf
Online blood donation management system project.pdf
 
Toll tax management system project report..pdf
Toll tax management system project report..pdfToll tax management system project report..pdf
Toll tax management system project report..pdf
 
2024 DevOps Pro Europe - Growing at the edge
2024 DevOps Pro Europe - Growing at the edge2024 DevOps Pro Europe - Growing at the edge
2024 DevOps Pro Europe - Growing at the edge
 
Natalia Rutkowska - BIM School Course in Kraków
Natalia Rutkowska - BIM School Course in KrakówNatalia Rutkowska - BIM School Course in Kraków
Natalia Rutkowska - BIM School Course in Kraków
 

Python-oop

  • 3. Object Oriented Programming concept  Module  Class  Object  Encapsulation  Inheritance  Abstraction  Polymorphism RTS tech
  • 4. Application • One application is made of multiple modules • A Module is a file with .py extension. • A module can define functions, classes and variables. RTS tech
  • 5. Module  Module is a file of .py extension RTS tech
  • 6. 6 Student.py Following is Student module which contains two methods add() and update( ) o def add_student( rollno, Name ): o print("Adding Student") o print('Name', Name ) o print(‘Rollno', rollno ) o return o def update_student(Name ): o print("Updating Student") o print('Name', Name ) o return RTS tech
  • 7. 7 • You can import a module by import statement in python program. We are importing Student.py module in TestStudent.py file. o import Student • Now we can use module functions: o Student.add_student(1,”Sonu”) o Student.add_student(2,”Monu”) TestStudent.py RTS tech
  • 8. from ... Import statement  We can import specific functions from a module using from ...import statement. o from Student import add,update o add(1,"Ram") o update("Shyam")  You can import all methods using * character  from Student import * RTS tech
  • 9. Module search path  When you import a module, python interpreter searches module in different directories in the following sequences:  The current directory.  If module is not found then searches each directory specified  in environment variable PYTHONPATH.  If all fails then python checks the default path.  You can set PYTHONPATH as per your app requirements  set PYTHONPATH =c:pythonlibl;c:pythonlib2; RTS tech
  • 10. Objects: Real world Entities  Object=Related attributes+ Related methods RTS tech
  • 11. Objects vs Class Attributes • Color • Brand • Price • … Method • take_Selfie() • Calling() • Messaging() RTS tech Virtual Entity Actual Entity
  • 12. Class  It is a structure of an Object.  Class contains related attributes and methods of an Object.  Class keyword is used to define a class.  Class contains the complete details about an object.  Ex.  Home  Pen  Chair RTS tech
  • 13. Object • When we create a class only description is created no memory is allocated. • We can create an variable of the class. • Variable is known as object(instance). • We can create multiple object of the class. RTS tech
  • 14. Define a class  ‘class’ keyword is used to define the class.  Class Mobile:  ‘contains all details about mobile’  The first line after the class name is a document String.  Class Members:  Attributes  Methods  Constructor  Destructor RTS tech
  • 15. Mobile  class Mobile:  "contains mobile information“  #class variables are shared by all instance  object_count=0  def __init__(self):#constructor  self.color = "" #instance attribute  self.brand=“”  Mobile.object_count+=1  def get_color(self): #instance Method  return self.color  def set_color(self,color):  self.color = color RTS tech
  • 16. TestMobile.py  Create Object(variable) of Mobile class.  We can create multiple object of the class.  m1=Mobile()  m2=Mobile()  m1.set_color("black")  Print Value of the Mobile  print("Count",Mobile.object_count)  print("color: ",m1.get_color()) RTS tech
  • 17. Built in Class Attributes  __doc__: to get doc string of the class.  __dict__: to get dictionary of the class members.  __bases__: to get base classes tuple.  __name__: to get class name.  __module__: to get module name. RTS tech
  • 18. Class attributes  print("Dictonary:",Mobile.__dict__)  print("Name:",Mobile.__name__)  print("Document string:",Mobile.__doc__)  print("Module:",Mobile.__module__)  print("Bases:",Mobile.__bases__) RTS tech
  • 19. Class(static) attributes  Class attributes are declared within a class but outside method.  class Mobile:  object_count=0  It is shared by all instance of the class.  Static variables got memory one time.  We can access class variable by class name.  Mobile.object_count+=1 RTS tech
  • 20. Instance (non-static) Attributes  Instance variables are define inside the constructor.  def __init__(self):#constructor  self.color =""  self.brand=“”  Instance variable get memory for each instance separately.  We can access instance variable with the instance name. RTS tech
  • 21. Constructor  Constructor is defined by __init__(self) method.  Each class has only one constructor method.  Constructor is used to initialize the class and instance variable.  It is executed at the time of object creation(instantiation process).  self keyword represent current instance. RTS tech
  • 22. Methods in a class  Method is used to write business logic.  Method is define by def keyword.  Instance method contains a self attribute to access instance variable.  Class method does not require self keyword.  We can access class method with the help of class name  class Mobile:  def get_color(self):  return self.color  def set_color(self,color):  self.color = color RTS tech
  • 23. __del__(self)  Destructor function remove an object from the memory.  __del__() method is used to create destructor in a class.  When an object is not in use the destructor function is automatically called.  def __del__(self):  name=self.__class__.__name__  print("Object is Destroyed {}".format(name)) RTS tech
  • 24. Object to string  We can convert an object into string form.  __str__(self) method is used to create an string function in a class.  When we print an object the address is printed  <__main__.Mobile object at 0x000001EA4D8670D0>  after creating __str__(self) method in a class , when we print an object the object is automatically converted into string representation. RTS tech
  • 25. Inheritance  It is a concept of OOP language.  It is use to define a class based on another class.  One class is known as Base or super class and another class is known as Derived or sub class.  Here Person is a Base class and Programmer, Doctor are Derived classes.  By default Each class has Object as Base Class.  Syntax: class Doctor(Person):  pass Person Programmer Doctor Person RTS tech
  • 26. Types of Inheritance Class A Class B Class C Class B Class A Class C Class B Class A Class A Class B Class C 1.Single Level 2.Multi Level 3.Multiple 4. Hierarchical RTS tech
  • 28. Mobile class  class Mobile:  counts=0  def __init__(self, name=None,color=None,im=0,price=0):  self.__name = name  self.__color = color  self.__price = price  self.__IMEI = im  Mobile.counts+=1  #setter and getter methods  def get_color(self):  return self.__color  def set_color(self, color):  self.__color = color RTS tech
  • 29. BasicPhone class  from mobile import Mobile  class BasicPhone(Mobile):  def __init__(self):  self.__keypad=“”  def get_keypad(self):  return self.__keypad  def set_keypad(self,keypad):  self.__keypad =keypad  def tuneRadio(self):  return "Tunning radio" RTS tech
  • 30. Create child class Instance  from basicPhone import BasicPhone  phone = BasicPhone()  phone.setColor("Black")  phone.setBrandName("Nokia")  phone.setPrice(2000)  phone.setKeypad(True)  print("--------Phone Info-------------")  print("Color ={}".format(phone.getColor()))  print("BrandName ={}".format(phone.getbrand()))  print("Price ={}".format(phone.getPrice()))  print("Radio {}".format(phone.tuneRadio()))  print("Keypad:{}".format(phone.get_keypad())) RTS tech
  • 31. How to call Parent Class Constructor?  from mobile import Mobile  class SmartPhone(Mobile):  def __init__(self,n,c,i,p,screen_size):  self.__screen_size=screen_size  # super(SmartPhone,self).__init__(n,c,i,p  #OR  super().__init__(n,c,i,p)  def get_ScreenSize(self):  return self.__screen_size  def set_ScreenSize(self,screen_size):  self.__screen_size = screen_size RTS tech
  • 32. Parent class constructor  from smartPhone import SmartPhone  sp=SmartPhone("REalMe","Black",12345671,20000,20)  print("Price {}".format(sp.get_price()))  print("Color {}".format(sp.get_color()))  print("IMEI No {}".format(sp.get_IMEI()))  print("Screen Size {}".format(sp.get_ScreenSize())) RTS tech
  • 33. Polymorphism  Having many Forms. RTS tech
  • 34. Types of polymorphism  Runtime  Method Overriding  Compile time  Method Overloading RTS tech
  • 36. Method Overriding(cont.)  Sub class can override the Super class Method.  class Mobile:  def answer(self):  print("Answer the call")  class BasicPhone:  def answer(self):  print(“Press the key to answer the call")  class SmartPhone:  def answer(self):  print(“Swipe right to answer the call") RTS tech
  • 38. Abstract class  Abstract class contains abstract method.  Abstract method has only method declaration no method definition  Different mobile phone has different implementation for answerCall() method.  We can not create instance of abstract class.  Child class will provide implementation to the abstract method. RTS tech
  • 39. Implementation  from abc import ABC,abstractmethod  class Mobile(ABC):  @abstractmethod  def answerCall(self):  pass  class BasicPhone:  def answer(self):  print(“Press the key to answer the call")  class SmartPhone:  def answer(self):  print(“Swipe right to answer the call") RTS tech
  • 40. Disclaimer  This is an educational presentation to enhance the skill of computer science students.  This presentation is available for free to computer science students.  Some internet images from different URLs are used in this presentation to simplify technical examples and correlate examples with the real world.  We are grateful to owners of these URLs and pictures.