KEMBAR78
Python-oop | PPTX
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

Python-oop

  • 1.
  • 2.
  • 3.
    Object Oriented Programmingconcept  Module  Class  Object  Encapsulation  Inheritance  Abstraction  Polymorphism RTS tech
  • 4.
    Application • One applicationis 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 isa file of .py extension RTS tech
  • 6.
    6 Student.py Following is Studentmodule 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 canimport 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 ... Importstatement  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 worldEntities  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 isa 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 wecreate 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 ClassAttributes  __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  Classattributes 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 isdefined 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 aclass  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 functionremove 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 isa 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 ClassA 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
  • 27.
  • 28.
    Mobile class  classMobile:  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  frommobile 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 classInstance  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 callParent 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.
  • 34.
    Types of polymorphism Runtime  Method Overriding  Compile time  Method Overloading RTS tech
  • 35.
  • 36.
    Method Overriding(cont.)  Subclass 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
  • 37.
  • 38.
    Abstract class  Abstractclass 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 abcimport 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 isan 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.
  • 41.