SlideShare a Scribd company logo
1 of 36
7/22/2014 VYBHAVA TECHNOLOGIES 1
Contents
> Differences Procedure vs Object Oriented Programming
> Features of OOP
> Fundamental Concepts of OOP in Python
> What is Class
> What is Object
> Methods in Classes
Instantiating objects with __init__
self
> Encapsulation
> Data Abstraction
> Public, Protected and Private Data
> Inheritance
> Polymorphism
> Operator Overloading
7/22/2014 VYBHAVA TECHNOLOGIES 2
Difference between Procedure Oriented and
Object Oriented Programming
Procedural programming creates a step by step program that
guides the application through a sequence of instructions. Each
instruction is executed in order.
Procedural programming also focuses on the idea that all
algorithms are executed with functions and data that the
programmer has access to and is able to change.
Object-Oriented programming is much more similar to the way
the real world works; it is analogous to the human brain. Each
program is made up of many entities called objects.
Instead, a message must be sent requesting the data, just like
people must ask one another for information; we cannot see
inside each other’s heads.
7/22/2014 VYBHAVA TECHNOLOGIES 3
Summarized the differences
Procedure Oriented Programming Object Oriented Progrmming
In POP, program is divided into small
parts called functions
In OOP, program is divided into parts
called objects.
POP follows Top Down approach OOP follows Bottom Up approach
POP does not have any proper way for
hiding data so it is less secure.
OOP provides Data Hiding so provides more
security
In POP, Overloading is not possible In OOP, overloading is possible in the form
of Function Overloading and Operator
Overloading
In POP, Most function uses Global
data for sharing that can be accessed
freely from function to function in the
system.
In OOP, data can not move easily from
function to function, it can be kept public or
private so we can control the access of data.
POP does not have any access specifier OOP has access specifiers named Public,
Private, Protected, etc.
7/22/2014 VYBHAVA TECHNOLOGIES 4
Featuers of OOP
Ability to simulate real-world event much more effectively
Code is reusable thus less code may have to be written
Data becomes active
Better able to create GUI (graphical user interface) applications
Programmers are able to produce faster, more accurate and better-
written applications
7/22/2014 VYBHAVA TECHNOLOGIES 5
Fundamental concepts of OOP in Python
The four major principles of object orientation are:
Encapsulation
Data Abstraction
Inheritance
Polymorphism
7/22/2014 VYBHAVA TECHNOLOGIES 6
What is an Object..?
 Objects are the basic run-time entities in an object-oriented
system.
They may represent a person, a place, a bank account, a table of
data or any item that the program must handle.
When a program is executed the objects interact by sending
messages to one another.
Objects have two components:
- Data (i.e., attributes)
- Behaviors (i.e., methods)
7/22/2014 VYBHAVA TECHNOLOGIES 7
Object Attributes and Methods Example
Object Attributes Object Methods
 Store the data for that object
 Example (taxi):
 Driver
 OnDuty
 NumPassengers
 Location
 Define the behaviors for the
object
 Example (taxi):
- PickUp
- DropOff
- GoOnDuty
- GoOffDuty
- GetDriver
- SetDriver
- GetNumPassengers
7/22/2014 VYBHAVA TECHNOLOGIES 8
What is a Class..?
A class is a special data type which defines how to build a certain
kind of object.
The class also stores some data items that are shared by all the
instances of this class
 Instances are objects that are created which follow the definition
given inside of the class
Python doesn’t use separate class interface definitions as in some
languages
You just define the class and then use it
7/22/2014 VYBHAVA TECHNOLOGIES 9
Methods in Classes
Define a method in a class by including function definitions
within the scope of the class block
There must be a special first argument self in all of method
definitions which gets bound to the calling instance
There is usually a special method called __init__ in most
classes
7/22/2014 VYBHAVA TECHNOLOGIES 10
A Simple Class def: Student
class student:
“““A class representing a student ”””
def __init__(self , n, a):
self.full_name = n
self.age = a
def get_age(self): #Method
return self.age
Define class:
 Class name, begin with capital letter, by convention
 object: class based on (Python built-in type)
Define a method
 Like defining a function
 Must have a special first parameter, self, which provides way
for a method to refer to object itself
7/22/2014 VYBHAVA TECHNOLOGIES 11
Instantiating Objects with ‘__init__’
 __init__ is the default constructor
__init__ serves as a constructor for the class. Usually
does some initialization work
An __init__ method can take any number of
arguments
However, the first argument self in the definition of
__init__ is special
7/22/2014 VYBHAVA TECHNOLOGIES 12
Self
The first argument of every method is a reference to the current
instance of the class
By convention, we name this argument self
In __init__, self refers to the object currently being created; so, in
other class methods, it refers to the instance whose method was
called
Similar to the keyword this in Java or C++
But Python uses self more often than Java uses this
You do not give a value for this parameter(self) when you call the
method, Python will provide it.
Continue…
7/22/2014 VYBHAVA TECHNOLOGIES 13
…Continue
Although you must specify self explicitly when defining the
method, you don’t include it when calling the method.
Python passes it for you automatically
Defining a method: Calling a method:
(this code inside a class definition.)
def get_age(self, num): >>> x.get_age(23)
self.age = num
7/22/2014 VYBHAVA TECHNOLOGIES 14
Deleting instances: No Need to “free”
7/22/2014 VYBHAVA TECHNOLOGIES 15
 When you are done with an object, you don’t have to delete
or free it explicitly.
 Python has automatic garbage collection.
 Python will automatically detect when all of the references to
a piece of memory have gone out of scope. Automatically
frees that memory.
 Generally works well, few memory leaks
 There’s also no “destructor” method for classes
Syntax for accessing attributes and methods
>>> f = student(“Python”, 14)
>>> f.full_name # Access attribute
“Python”
>>> f.get_age() # Access a method
14
7/22/2014 VYBHAVA TECHNOLOGIES 16
Simple Program for Class and Object
class Student:
# Initializing the variables
def __init__(self,name,age):
self.fullname=name
self.sage=age
# Display the entered data such as Students name and age
def display(self):
print 'Student FullName: %s' %(self.fullname)
print 'Stuent Age: %d'%(self.sage)
# S1,S2 and S3 objects
# S1,S2 and S3 are three different student details and age
s1=Student('Python',14)
s1.display()
s2=Student('Jython',23)
s2.display()
s3=Student('Objects',45)
s3.display()
7/22/2014 VYBHAVA TECHNOLOGIES 17
Output for the Sample Code
7/22/2014 VYBHAVA TECHNOLOGIES 18
Encapsulation
Important advantage of OOP consists in the encapsulation
of data. We can say that object-oriented programming
relies heavily on encapsulation.
The terms encapsulation and abstraction (also data hiding)
are often used as synonyms. They are nearly synonymous,
i.e. abstraction is achieved though encapsulation.
Data hiding and encapsulation are the same concept, so it's
correct to use them as synonyms
Generally speaking encapsulation is the mechanism for
restricting the access to some of an objects's components,
this means, that the internal representation of an object
can't be seen from outside of the objects definition.
7/22/2014 VYBHAVA TECHNOLOGIES 19
 Access to this data is typically only achieved through
special methods: Getters and Setters
By using solely get() and set() methods, we can make sure
that the internal data cannot be accidentally set into an
inconsistent or invalid state.
C++, Java, and C# rely on the public, private,
and protected keywords in order to implement variable
scoping and encapsulation
 It's nearly always possible to circumvent this protection
mechanism
7/22/2014 VYBHAVA TECHNOLOGIES 20
Public, Protected and Private Data
7/22/2014 VYBHAVA TECHNOLOGIES 21
 If an identifier doesn't start with an underscore character "_" it
can be accessed from outside, i.e. the value can be read and
changed
 Data can be protected by making members private or protected.
Instance variable names starting with two underscore characters
cannot be accessed from outside of the class.
 At least not directly, but they can be accessed through private
name mangling.
 That means, private data __A can be accessed by the following
name construct: instance_name._classname__A
 If an identifier is only preceded by one underscore character, it
is a protected member.
 Protected members can be accessed like public members from
outside of class
Example:
class Encapsulation(object):
def __init__(self, a, b, c):
self.public = a
self._protected = b
self.__private = c
7/22/2014 VYBHAVA TECHNOLOGIES 22
The following interactive sessions shows the behavior of public,
protected and private members:
>>> x = Encapsulation(11,13,17)
>>> x.public
11
>>> x._protected
13
>>> x._protected = 23
>>> x._protected
23
>>> x.__private
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'Encapsulation' object has no attribute '__private‘
>>>
7/22/2014 VYBHAVA TECHNOLOGIES 23
The following table shows the different behavior Public,
Protected and Private Data
7/22/2014 VYBHAVA TECHNOLOGIES 24
Name Notation Behavior
name Public Can be accessed from inside and
outside
_name Protected Like a public member, but they
shouldn't be directly accessed from
outside
__name Private Can't be seen and accessed from
outside
Inheritance
 Inheritance is a powerful feature in object oriented programming
 It refers to defining a new class with little or no modification to an
existing class.
 The new class is called derived (or child) class and the one from which
it inherits is called the base (or parent) class.
 Derived class inherits features from the base class, adding new features
to it.
 This results into re-usability of code.
Syntax:
class Baseclass(Object):
body_of_base_class
class DerivedClass(BaseClass):
body_of_derived_clas
7/22/2014 VYBHAVA TECHNOLOGIES 25
7/22/2014 VYBHAVA TECHNOLOGIES 26
While designing a inheritance concept, following key pointes keep it
in mind
A sub type never implements less functionality than the super type
Inheritance should never be more than two levels deep
We use inheritance when we want to avoid redundant code.
Two built-in functions isinstance() and issubclass() are used
to check inheritances.
Function isinstance() returns True if the object is an instance
of the class or other classes derived from it.
Each and every class in Python inherits from the base
class object.
7/22/2014 VYBHAVA TECHNOLOGIES 27
Sample code for Inheritance
7/22/2014 VYBHAVA TECHNOLOGIES 28
class Person(object):
def __init__(self,name,age):
self.name=name
self.age=age
def show(self):
print 'Person Name: %s' %(self.name)
print 'Person Age: %s' %(self.age)
class Employe(Person):
def __init__(self,name,age,company,sal):
self.company=company
self.sal=sal
super(Employe,self).__init__(name,age)
def __repr__(self):
return str
(self.name+self.age+self.company+self.sal)
def showme(self):
super(Employe,self).show()
print 'Company Name: %s'%(self.company)
print 'Employe Salary per Annum: %s' %(self.sal)
print 'n'
empdict={‘guido':['45',‘PYTHON','500000'],
‘van':['25',‘JYTHON','200000'],
’rossum':['35',‘ABC','400000']}
for key,value in empdict.iteritems():
print key,value
emp=Employe(key,value[0],value[1],value[2])
emp.showme()
Polymorphism
Polymorphism in Latin word which made up of ‘ploy’
means many and ‘morphs’ means forms
From the Greek , Polymorphism means many(poly)
shapes (morph)
 This is something similar to a word having several different
meanings depending on the context
 Generally speaking, polymorphism means that a method or
function is able to cope with different types of input.
7/22/2014 VYBHAVA TECHNOLOGIES 29
A simple word ‘Cut’ can have different meaning
depending where it is used
7/22/2014 VYBHAVA TECHNOLOGIES 30
Cut
Surgeon: The Surgeon
would begin to make an
incision
Hair Stylist: The Hair
Stylist would begin to cut
someone’s hair
Actor: The actor would
abruptly stop acting out the
current scene, awaiting
directional guidance
If any body says “Cut” to these people
In OOP , Polymorphism is the characteristic of being able to
assign a different meaning to a particular symbol or operator in
different contexts specifically to allow an entity such as a
variable, a function or an object to have more than one form.
There are two kinds of Polymorphism
Overloading :
Two or more methods with different signatures
Overriding:
Replacing an inherited method with another having the same
signature
7/22/2014 VYBHAVA TECHNOLOGIES 31
A Sample Program for Polymorphism
7/22/2014 VYBHAVA TECHNOLOGIES 32
class Person:
def __init__(self, name): # Constructor of the class
self.name = name
def designation(self): # Abstract method, defined by convention only
raise NotImplementedError("Subclass must implement abstract method")
class Employe(Person):
def designation(self):
return 'Software Engineer‘
class Doctor(Person):
def designation(self):
return 'Cardiologist‘
class Student(Person):
def designation(self):
return 'Graduate Engineer'
persons = [Employe('Guido Van Rossum'),Doctor('Chalapathi'),Student('Robert')]
for person in persons:
print person.name + ': ' + person.designation()
Python operators work for built-in classes.
But same operator behaves differently with different types. For
example, the + operator will, perform arithmetic addition on
two numbers, merge two lists and concatenate two strings. This
feature in Python, that allows same operator to have different
meaning according to the context is called operator overloading
One final thing to mention about operator overloading is that
you can make your custom methods do whatever you want.
However, common practice is to follow the structure of the
built-in methods.
7/22/2014 VYBHAVA TECHNOLOGIES 33
Operator Overloading
Operator Overloading Sample Program
class Point:
def __init__(self,x,y):
self.x=x
self.y=y
def __sub__(self,other):
x=self.x-other.x
y=self.y-other.y
return Point(x,y)
def __mul__(self,other):
x=self.x*other.x
y=self.y*other.y
return Point(x,y)
def __pow__(self,other):
x=self.x**other.x
y=self.y**other.y
return Point(x,y)
def __str__(self):
return "({0},{1})".format(self.x , self.y)
p1=Point(5,4)
p2=Point(3,2)
sub=p1-p2
mul=p1*p2
pow=p1**p2
print sub
print mul
print pow
7/22/2014 VYBHAVA TECHNOLOGIES 34
Explanation for Operator Overloading Sample Program
What actually happens is that, when you do p1 - p2, Python will
call p1.__sub__(p2) which in turn is Point.__sub__(p1,p2).
Similarly, we can overload other operators as well. The special
function that we need to implement is tabulated below.
7/22/2014 VYBHAVA TECHNOLOGIES 35
Operator Expression Internally
Addition p1 + p2 p1.__add__(p2)
Subtraction p1 – p2 p1.__sub__(p2)
Multiplication p1 * p2 p1.__mul__(p2)
Power p1 ** p2 p1.__pow__(p2)
Division p1 / p2 p1.__truediv__(p2)
7/22/2014 VYBHAVA TECHNOLOGIES 36
Output for Operator Overloading Sample Program

More Related Content

What's hot

Functions in python
Functions in pythonFunctions in python
Functions in pythoncolorsof
 
Functions in python slide share
Functions in python slide shareFunctions in python slide share
Functions in python slide shareDevashish Kumar
 
Basics of Object Oriented Programming in Python
Basics of Object Oriented Programming in PythonBasics of Object Oriented Programming in Python
Basics of Object Oriented Programming in PythonSujith Kumar
 
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYAPYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYAMaulik Borsaniya
 
Python – Object Oriented Programming
Python – Object Oriented Programming Python – Object Oriented Programming
Python – Object Oriented Programming Raghunath A
 
CLASS OBJECT AND INHERITANCE IN PYTHON
CLASS OBJECT AND INHERITANCE IN PYTHONCLASS OBJECT AND INHERITANCE IN PYTHON
CLASS OBJECT AND INHERITANCE IN PYTHONLalitkumar_98
 
Functions and modules in python
Functions and modules in pythonFunctions and modules in python
Functions and modules in pythonKarin Lagesen
 
Python Dictionaries and Sets
Python Dictionaries and SetsPython Dictionaries and Sets
Python Dictionaries and SetsNicole Ryan
 
Basic data structures in python
Basic data structures in pythonBasic data structures in python
Basic data structures in pythonCeline George
 
Datatypes in python
Datatypes in pythonDatatypes in python
Datatypes in pythoneShikshak
 
String Manipulation in Python
String Manipulation in PythonString Manipulation in Python
String Manipulation in PythonPooja B S
 

What's hot (20)

Python set
Python setPython set
Python set
 
Functions in python
Functions in pythonFunctions in python
Functions in python
 
Functions in python slide share
Functions in python slide shareFunctions in python slide share
Functions in python slide share
 
Basics of Object Oriented Programming in Python
Basics of Object Oriented Programming in PythonBasics of Object Oriented Programming in Python
Basics of Object Oriented Programming in Python
 
Python functions
Python functionsPython functions
Python functions
 
Oop concepts in python
Oop concepts in pythonOop concepts in python
Oop concepts in python
 
Strings in python
Strings in pythonStrings in python
Strings in python
 
Python Flow Control
Python Flow ControlPython Flow Control
Python Flow Control
 
Chapter 05 classes and objects
Chapter 05 classes and objectsChapter 05 classes and objects
Chapter 05 classes and objects
 
Python Scipy Numpy
Python Scipy NumpyPython Scipy Numpy
Python Scipy Numpy
 
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYAPYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
 
Python – Object Oriented Programming
Python – Object Oriented Programming Python – Object Oriented Programming
Python – Object Oriented Programming
 
CLASS OBJECT AND INHERITANCE IN PYTHON
CLASS OBJECT AND INHERITANCE IN PYTHONCLASS OBJECT AND INHERITANCE IN PYTHON
CLASS OBJECT AND INHERITANCE IN PYTHON
 
Functions and modules in python
Functions and modules in pythonFunctions and modules in python
Functions and modules in python
 
Python Dictionaries and Sets
Python Dictionaries and SetsPython Dictionaries and Sets
Python Dictionaries and Sets
 
Chapter 03 python libraries
Chapter 03 python librariesChapter 03 python libraries
Chapter 03 python libraries
 
Basic data structures in python
Basic data structures in pythonBasic data structures in python
Basic data structures in python
 
Python libraries
Python librariesPython libraries
Python libraries
 
Datatypes in python
Datatypes in pythonDatatypes in python
Datatypes in python
 
String Manipulation in Python
String Manipulation in PythonString Manipulation in Python
String Manipulation in Python
 

Similar to Object Oriented Programming in Python

OOP in Python, a beginners guide..........
OOP in Python, a beginners guide..........OOP in Python, a beginners guide..........
OOP in Python, a beginners guide..........FerryKemperman
 
Object Oriented Programming
Object Oriented ProgrammingObject Oriented Programming
Object Oriented ProgrammingIqra khalil
 
Chapter 04 object oriented programming
Chapter 04 object oriented programmingChapter 04 object oriented programming
Chapter 04 object oriented programmingPraveen M Jigajinni
 
PHP OOP Lecture - 01.pptx
PHP OOP Lecture - 01.pptxPHP OOP Lecture - 01.pptx
PHP OOP Lecture - 01.pptxAtikur Rahman
 
Object Oriented Programming All Unit Notes
Object Oriented Programming All Unit NotesObject Oriented Programming All Unit Notes
Object Oriented Programming All Unit NotesBalamuruganV28
 
OOP interview questions & answers.
OOP interview questions & answers.OOP interview questions & answers.
OOP interview questions & answers.Questpond
 
Object Oriented programming Using Python.pdf
Object Oriented programming Using Python.pdfObject Oriented programming Using Python.pdf
Object Oriented programming Using Python.pdfRishuRaj953240
 
9-_Object_Oriented_Programming_Using_Python.pdf
9-_Object_Oriented_Programming_Using_Python.pdf9-_Object_Oriented_Programming_Using_Python.pdf
9-_Object_Oriented_Programming_Using_Python.pdfanaveenkumar4
 
OOP in Java Presentation.pptx
OOP in Java Presentation.pptxOOP in Java Presentation.pptx
OOP in Java Presentation.pptxmrxyz19
 
1669609053088_oops_final.pptx
1669609053088_oops_final.pptx1669609053088_oops_final.pptx
1669609053088_oops_final.pptxPandeeswariKannan
 
CSc investigatory project
CSc investigatory projectCSc investigatory project
CSc investigatory projectDIVYANSHU KUMAR
 
Object oriented programming in python
Object oriented programming in pythonObject oriented programming in python
Object oriented programming in pythonnitamhaske
 

Similar to Object Oriented Programming in Python (20)

OOP in Python, a beginners guide..........
OOP in Python, a beginners guide..........OOP in Python, a beginners guide..........
OOP in Python, a beginners guide..........
 
Php oop (1)
Php oop (1)Php oop (1)
Php oop (1)
 
Ah java-ppt2
Ah java-ppt2Ah java-ppt2
Ah java-ppt2
 
Object Oriented Programming
Object Oriented ProgrammingObject Oriented Programming
Object Oriented Programming
 
Chapter 04 object oriented programming
Chapter 04 object oriented programmingChapter 04 object oriented programming
Chapter 04 object oriented programming
 
Basic concept of OOP's
Basic concept of OOP'sBasic concept of OOP's
Basic concept of OOP's
 
PHP OOP Lecture - 01.pptx
PHP OOP Lecture - 01.pptxPHP OOP Lecture - 01.pptx
PHP OOP Lecture - 01.pptx
 
Object Oriented Programming All Unit Notes
Object Oriented Programming All Unit NotesObject Oriented Programming All Unit Notes
Object Oriented Programming All Unit Notes
 
OOP interview questions & answers.
OOP interview questions & answers.OOP interview questions & answers.
OOP interview questions & answers.
 
MCA NOTES.pdf
MCA NOTES.pdfMCA NOTES.pdf
MCA NOTES.pdf
 
Principles of oop
Principles of oopPrinciples of oop
Principles of oop
 
Object Oriented programming Using Python.pdf
Object Oriented programming Using Python.pdfObject Oriented programming Using Python.pdf
Object Oriented programming Using Python.pdf
 
9-_Object_Oriented_Programming_Using_Python.pdf
9-_Object_Oriented_Programming_Using_Python.pdf9-_Object_Oriented_Programming_Using_Python.pdf
9-_Object_Oriented_Programming_Using_Python.pdf
 
OOP in Java Presentation.pptx
OOP in Java Presentation.pptxOOP in Java Presentation.pptx
OOP in Java Presentation.pptx
 
CS3391 -OOP -UNIT – I NOTES FINAL.pdf
CS3391 -OOP -UNIT – I  NOTES FINAL.pdfCS3391 -OOP -UNIT – I  NOTES FINAL.pdf
CS3391 -OOP -UNIT – I NOTES FINAL.pdf
 
1669609053088_oops_final.pptx
1669609053088_oops_final.pptx1669609053088_oops_final.pptx
1669609053088_oops_final.pptx
 
CSc investigatory project
CSc investigatory projectCSc investigatory project
CSc investigatory project
 
Object oriented programming in python
Object oriented programming in pythonObject oriented programming in python
Object oriented programming in python
 
C++ & VISUAL C++
C++ & VISUAL C++ C++ & VISUAL C++
C++ & VISUAL C++
 
130704798265658191
130704798265658191130704798265658191
130704798265658191
 

Recently uploaded

SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024BookNet Canada
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Neo4j
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
 

Recently uploaded (20)

SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptxVulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
 

Object Oriented Programming in Python

  • 2. Contents > Differences Procedure vs Object Oriented Programming > Features of OOP > Fundamental Concepts of OOP in Python > What is Class > What is Object > Methods in Classes Instantiating objects with __init__ self > Encapsulation > Data Abstraction > Public, Protected and Private Data > Inheritance > Polymorphism > Operator Overloading 7/22/2014 VYBHAVA TECHNOLOGIES 2
  • 3. Difference between Procedure Oriented and Object Oriented Programming Procedural programming creates a step by step program that guides the application through a sequence of instructions. Each instruction is executed in order. Procedural programming also focuses on the idea that all algorithms are executed with functions and data that the programmer has access to and is able to change. Object-Oriented programming is much more similar to the way the real world works; it is analogous to the human brain. Each program is made up of many entities called objects. Instead, a message must be sent requesting the data, just like people must ask one another for information; we cannot see inside each other’s heads. 7/22/2014 VYBHAVA TECHNOLOGIES 3
  • 4. Summarized the differences Procedure Oriented Programming Object Oriented Progrmming In POP, program is divided into small parts called functions In OOP, program is divided into parts called objects. POP follows Top Down approach OOP follows Bottom Up approach POP does not have any proper way for hiding data so it is less secure. OOP provides Data Hiding so provides more security In POP, Overloading is not possible In OOP, overloading is possible in the form of Function Overloading and Operator Overloading In POP, Most function uses Global data for sharing that can be accessed freely from function to function in the system. In OOP, data can not move easily from function to function, it can be kept public or private so we can control the access of data. POP does not have any access specifier OOP has access specifiers named Public, Private, Protected, etc. 7/22/2014 VYBHAVA TECHNOLOGIES 4
  • 5. Featuers of OOP Ability to simulate real-world event much more effectively Code is reusable thus less code may have to be written Data becomes active Better able to create GUI (graphical user interface) applications Programmers are able to produce faster, more accurate and better- written applications 7/22/2014 VYBHAVA TECHNOLOGIES 5
  • 6. Fundamental concepts of OOP in Python The four major principles of object orientation are: Encapsulation Data Abstraction Inheritance Polymorphism 7/22/2014 VYBHAVA TECHNOLOGIES 6
  • 7. What is an Object..?  Objects are the basic run-time entities in an object-oriented system. They may represent a person, a place, a bank account, a table of data or any item that the program must handle. When a program is executed the objects interact by sending messages to one another. Objects have two components: - Data (i.e., attributes) - Behaviors (i.e., methods) 7/22/2014 VYBHAVA TECHNOLOGIES 7
  • 8. Object Attributes and Methods Example Object Attributes Object Methods  Store the data for that object  Example (taxi):  Driver  OnDuty  NumPassengers  Location  Define the behaviors for the object  Example (taxi): - PickUp - DropOff - GoOnDuty - GoOffDuty - GetDriver - SetDriver - GetNumPassengers 7/22/2014 VYBHAVA TECHNOLOGIES 8
  • 9. What is a Class..? A class is a special data type which defines how to build a certain kind of object. The class also stores some data items that are shared by all the instances of this class  Instances are objects that are created which follow the definition given inside of the class Python doesn’t use separate class interface definitions as in some languages You just define the class and then use it 7/22/2014 VYBHAVA TECHNOLOGIES 9
  • 10. Methods in Classes Define a method in a class by including function definitions within the scope of the class block There must be a special first argument self in all of method definitions which gets bound to the calling instance There is usually a special method called __init__ in most classes 7/22/2014 VYBHAVA TECHNOLOGIES 10
  • 11. A Simple Class def: Student class student: “““A class representing a student ””” def __init__(self , n, a): self.full_name = n self.age = a def get_age(self): #Method return self.age Define class:  Class name, begin with capital letter, by convention  object: class based on (Python built-in type) Define a method  Like defining a function  Must have a special first parameter, self, which provides way for a method to refer to object itself 7/22/2014 VYBHAVA TECHNOLOGIES 11
  • 12. Instantiating Objects with ‘__init__’  __init__ is the default constructor __init__ serves as a constructor for the class. Usually does some initialization work An __init__ method can take any number of arguments However, the first argument self in the definition of __init__ is special 7/22/2014 VYBHAVA TECHNOLOGIES 12
  • 13. Self The first argument of every method is a reference to the current instance of the class By convention, we name this argument self In __init__, self refers to the object currently being created; so, in other class methods, it refers to the instance whose method was called Similar to the keyword this in Java or C++ But Python uses self more often than Java uses this You do not give a value for this parameter(self) when you call the method, Python will provide it. Continue… 7/22/2014 VYBHAVA TECHNOLOGIES 13
  • 14. …Continue Although you must specify self explicitly when defining the method, you don’t include it when calling the method. Python passes it for you automatically Defining a method: Calling a method: (this code inside a class definition.) def get_age(self, num): >>> x.get_age(23) self.age = num 7/22/2014 VYBHAVA TECHNOLOGIES 14
  • 15. Deleting instances: No Need to “free” 7/22/2014 VYBHAVA TECHNOLOGIES 15  When you are done with an object, you don’t have to delete or free it explicitly.  Python has automatic garbage collection.  Python will automatically detect when all of the references to a piece of memory have gone out of scope. Automatically frees that memory.  Generally works well, few memory leaks  There’s also no “destructor” method for classes
  • 16. Syntax for accessing attributes and methods >>> f = student(“Python”, 14) >>> f.full_name # Access attribute “Python” >>> f.get_age() # Access a method 14 7/22/2014 VYBHAVA TECHNOLOGIES 16
  • 17. Simple Program for Class and Object class Student: # Initializing the variables def __init__(self,name,age): self.fullname=name self.sage=age # Display the entered data such as Students name and age def display(self): print 'Student FullName: %s' %(self.fullname) print 'Stuent Age: %d'%(self.sage) # S1,S2 and S3 objects # S1,S2 and S3 are three different student details and age s1=Student('Python',14) s1.display() s2=Student('Jython',23) s2.display() s3=Student('Objects',45) s3.display() 7/22/2014 VYBHAVA TECHNOLOGIES 17
  • 18. Output for the Sample Code 7/22/2014 VYBHAVA TECHNOLOGIES 18
  • 19. Encapsulation Important advantage of OOP consists in the encapsulation of data. We can say that object-oriented programming relies heavily on encapsulation. The terms encapsulation and abstraction (also data hiding) are often used as synonyms. They are nearly synonymous, i.e. abstraction is achieved though encapsulation. Data hiding and encapsulation are the same concept, so it's correct to use them as synonyms Generally speaking encapsulation is the mechanism for restricting the access to some of an objects's components, this means, that the internal representation of an object can't be seen from outside of the objects definition. 7/22/2014 VYBHAVA TECHNOLOGIES 19
  • 20.  Access to this data is typically only achieved through special methods: Getters and Setters By using solely get() and set() methods, we can make sure that the internal data cannot be accidentally set into an inconsistent or invalid state. C++, Java, and C# rely on the public, private, and protected keywords in order to implement variable scoping and encapsulation  It's nearly always possible to circumvent this protection mechanism 7/22/2014 VYBHAVA TECHNOLOGIES 20
  • 21. Public, Protected and Private Data 7/22/2014 VYBHAVA TECHNOLOGIES 21  If an identifier doesn't start with an underscore character "_" it can be accessed from outside, i.e. the value can be read and changed  Data can be protected by making members private or protected. Instance variable names starting with two underscore characters cannot be accessed from outside of the class.  At least not directly, but they can be accessed through private name mangling.  That means, private data __A can be accessed by the following name construct: instance_name._classname__A
  • 22.  If an identifier is only preceded by one underscore character, it is a protected member.  Protected members can be accessed like public members from outside of class Example: class Encapsulation(object): def __init__(self, a, b, c): self.public = a self._protected = b self.__private = c 7/22/2014 VYBHAVA TECHNOLOGIES 22
  • 23. The following interactive sessions shows the behavior of public, protected and private members: >>> x = Encapsulation(11,13,17) >>> x.public 11 >>> x._protected 13 >>> x._protected = 23 >>> x._protected 23 >>> x.__private Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'Encapsulation' object has no attribute '__private‘ >>> 7/22/2014 VYBHAVA TECHNOLOGIES 23
  • 24. The following table shows the different behavior Public, Protected and Private Data 7/22/2014 VYBHAVA TECHNOLOGIES 24 Name Notation Behavior name Public Can be accessed from inside and outside _name Protected Like a public member, but they shouldn't be directly accessed from outside __name Private Can't be seen and accessed from outside
  • 25. Inheritance  Inheritance is a powerful feature in object oriented programming  It refers to defining a new class with little or no modification to an existing class.  The new class is called derived (or child) class and the one from which it inherits is called the base (or parent) class.  Derived class inherits features from the base class, adding new features to it.  This results into re-usability of code. Syntax: class Baseclass(Object): body_of_base_class class DerivedClass(BaseClass): body_of_derived_clas 7/22/2014 VYBHAVA TECHNOLOGIES 25
  • 26. 7/22/2014 VYBHAVA TECHNOLOGIES 26 While designing a inheritance concept, following key pointes keep it in mind A sub type never implements less functionality than the super type Inheritance should never be more than two levels deep We use inheritance when we want to avoid redundant code.
  • 27. Two built-in functions isinstance() and issubclass() are used to check inheritances. Function isinstance() returns True if the object is an instance of the class or other classes derived from it. Each and every class in Python inherits from the base class object. 7/22/2014 VYBHAVA TECHNOLOGIES 27
  • 28. Sample code for Inheritance 7/22/2014 VYBHAVA TECHNOLOGIES 28 class Person(object): def __init__(self,name,age): self.name=name self.age=age def show(self): print 'Person Name: %s' %(self.name) print 'Person Age: %s' %(self.age) class Employe(Person): def __init__(self,name,age,company,sal): self.company=company self.sal=sal super(Employe,self).__init__(name,age) def __repr__(self): return str (self.name+self.age+self.company+self.sal) def showme(self): super(Employe,self).show() print 'Company Name: %s'%(self.company) print 'Employe Salary per Annum: %s' %(self.sal) print 'n' empdict={‘guido':['45',‘PYTHON','500000'], ‘van':['25',‘JYTHON','200000'], ’rossum':['35',‘ABC','400000']} for key,value in empdict.iteritems(): print key,value emp=Employe(key,value[0],value[1],value[2]) emp.showme()
  • 29. Polymorphism Polymorphism in Latin word which made up of ‘ploy’ means many and ‘morphs’ means forms From the Greek , Polymorphism means many(poly) shapes (morph)  This is something similar to a word having several different meanings depending on the context  Generally speaking, polymorphism means that a method or function is able to cope with different types of input. 7/22/2014 VYBHAVA TECHNOLOGIES 29
  • 30. A simple word ‘Cut’ can have different meaning depending where it is used 7/22/2014 VYBHAVA TECHNOLOGIES 30 Cut Surgeon: The Surgeon would begin to make an incision Hair Stylist: The Hair Stylist would begin to cut someone’s hair Actor: The actor would abruptly stop acting out the current scene, awaiting directional guidance If any body says “Cut” to these people
  • 31. In OOP , Polymorphism is the characteristic of being able to assign a different meaning to a particular symbol or operator in different contexts specifically to allow an entity such as a variable, a function or an object to have more than one form. There are two kinds of Polymorphism Overloading : Two or more methods with different signatures Overriding: Replacing an inherited method with another having the same signature 7/22/2014 VYBHAVA TECHNOLOGIES 31
  • 32. A Sample Program for Polymorphism 7/22/2014 VYBHAVA TECHNOLOGIES 32 class Person: def __init__(self, name): # Constructor of the class self.name = name def designation(self): # Abstract method, defined by convention only raise NotImplementedError("Subclass must implement abstract method") class Employe(Person): def designation(self): return 'Software Engineer‘ class Doctor(Person): def designation(self): return 'Cardiologist‘ class Student(Person): def designation(self): return 'Graduate Engineer' persons = [Employe('Guido Van Rossum'),Doctor('Chalapathi'),Student('Robert')] for person in persons: print person.name + ': ' + person.designation()
  • 33. Python operators work for built-in classes. But same operator behaves differently with different types. For example, the + operator will, perform arithmetic addition on two numbers, merge two lists and concatenate two strings. This feature in Python, that allows same operator to have different meaning according to the context is called operator overloading One final thing to mention about operator overloading is that you can make your custom methods do whatever you want. However, common practice is to follow the structure of the built-in methods. 7/22/2014 VYBHAVA TECHNOLOGIES 33 Operator Overloading
  • 34. Operator Overloading Sample Program class Point: def __init__(self,x,y): self.x=x self.y=y def __sub__(self,other): x=self.x-other.x y=self.y-other.y return Point(x,y) def __mul__(self,other): x=self.x*other.x y=self.y*other.y return Point(x,y) def __pow__(self,other): x=self.x**other.x y=self.y**other.y return Point(x,y) def __str__(self): return "({0},{1})".format(self.x , self.y) p1=Point(5,4) p2=Point(3,2) sub=p1-p2 mul=p1*p2 pow=p1**p2 print sub print mul print pow 7/22/2014 VYBHAVA TECHNOLOGIES 34
  • 35. Explanation for Operator Overloading Sample Program What actually happens is that, when you do p1 - p2, Python will call p1.__sub__(p2) which in turn is Point.__sub__(p1,p2). Similarly, we can overload other operators as well. The special function that we need to implement is tabulated below. 7/22/2014 VYBHAVA TECHNOLOGIES 35 Operator Expression Internally Addition p1 + p2 p1.__add__(p2) Subtraction p1 – p2 p1.__sub__(p2) Multiplication p1 * p2 p1.__mul__(p2) Power p1 ** p2 p1.__pow__(p2) Division p1 / p2 p1.__truediv__(p2)
  • 36. 7/22/2014 VYBHAVA TECHNOLOGIES 36 Output for Operator Overloading Sample Program

Editor's Notes

  1. Need improve difference between protected vs public/private