SlideShare a Scribd company logo
7/26/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/26/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/26/2014 VYBHAVA TECHNOLOGIES 3
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/26/2014 VYBHAVA TECHNOLOGIES 4
Fundamental concepts of OOP in Python
The four major principles of object orientation are:
Encapsulation
Data Abstraction
Inheritance
Polymorphism
7/26/2014 VYBHAVA TECHNOLOGIES 5
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/26/2014 VYBHAVA TECHNOLOGIES 6
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/26/2014 VYBHAVA TECHNOLOGIES 7
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/26/2014 VYBHAVA TECHNOLOGIES 8
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/26/2014 VYBHAVA TECHNOLOGIES 9
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/26/2014 VYBHAVA TECHNOLOGIES 10
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/26/2014 VYBHAVA TECHNOLOGIES 11
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/26/2014 VYBHAVA TECHNOLOGIES 12
…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/26/2014 VYBHAVA TECHNOLOGIES 13
Deleting instances: No Need to “free”
7/26/2014 VYBHAVA TECHNOLOGIES 14
 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/26/2014 VYBHAVA TECHNOLOGIES 15
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/26/2014 VYBHAVA TECHNOLOGIES 16
 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/26/2014 VYBHAVA TECHNOLOGIES 17
Public, Protected and Private Data
7/26/2014 VYBHAVA TECHNOLOGIES 18
 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/26/2014 VYBHAVA TECHNOLOGIES 19
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/26/2014 VYBHAVA TECHNOLOGIES 20
The following table shows the different behavior Public,
Protected and Private Data
7/26/2014 VYBHAVA TECHNOLOGIES 21
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/26/2014 VYBHAVA TECHNOLOGIES 22
7/26/2014 VYBHAVA TECHNOLOGIES 23
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/26/2014 VYBHAVA TECHNOLOGIES 24
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/26/2014 VYBHAVA TECHNOLOGIES 25
A simple word ‘Cut’ can have different meaning
depending where it is used
7/26/2014 VYBHAVA TECHNOLOGIES 26
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/26/2014 VYBHAVA TECHNOLOGIES 27
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/26/2014 VYBHAVA TECHNOLOGIES 28
Operator Overloading
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/26/2014 VYBHAVA TECHNOLOGIES 29
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)

More Related Content

What's hot

Wrapper class
Wrapper classWrapper class
Wrapper class
kamal kotecha
 
Interface in java
Interface in javaInterface in java
Interface in java
PhD Research Scholar
 
Object Oriented Programming in Python
Object Oriented Programming in PythonObject Oriented Programming in Python
Object Oriented Programming in Python
Sujith Kumar
 
classes and objects in C++
classes and objects in C++classes and objects in C++
classes and objects in C++
HalaiHansaika
 
Chapter 07 inheritance
Chapter 07 inheritanceChapter 07 inheritance
Chapter 07 inheritance
Praveen M Jigajinni
 
Object Oriented Programming
Object Oriented ProgrammingObject Oriented Programming
Object Oriented Programming
Iqra khalil
 
Python tuple
Python   tuplePython   tuple
Python tuple
Mohammed Sikander
 
oops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaoops concept in java | object oriented programming in java
oops concept in java | object oriented programming in java
CPD INDIA
 
C++ OOPS Concept
C++ OOPS ConceptC++ OOPS Concept
C++ OOPS Concept
Boopathi K
 
Strings in python
Strings in pythonStrings in python
Strings in python
Prabhakaran V M
 
Object Oriented Programming Using C++
Object Oriented Programming Using C++Object Oriented Programming Using C++
Object Oriented Programming Using C++
Muhammad Waqas
 
Python exception handling
Python   exception handlingPython   exception handling
Python exception handling
Mohammed Sikander
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++
Vineeta Garg
 
Python-Inheritance.pptx
Python-Inheritance.pptxPython-Inheritance.pptx
Python-Inheritance.pptx
Karudaiyar Ganapathy
 
Static Data Members and Member Functions
Static Data Members and Member FunctionsStatic Data Members and Member Functions
Static Data Members and Member Functions
MOHIT AGARWAL
 
Command line arguments
Command line argumentsCommand line arguments
Command line arguments
Ashok Raj
 
File handling in Python
File handling in PythonFile handling in Python
File handling in Python
Megha V
 
Data Structures in Python
Data Structures in PythonData Structures in Python
Data Structures in Python
Devashish Kumar
 

What's hot (20)

Wrapper class
Wrapper classWrapper class
Wrapper class
 
Interface in java
Interface in javaInterface in java
Interface in java
 
Object Oriented Programming in Python
Object Oriented Programming in PythonObject Oriented Programming in Python
Object Oriented Programming in Python
 
classes and objects in C++
classes and objects in C++classes and objects in C++
classes and objects in C++
 
Chapter 07 inheritance
Chapter 07 inheritanceChapter 07 inheritance
Chapter 07 inheritance
 
Object Oriented Programming
Object Oriented ProgrammingObject Oriented Programming
Object Oriented Programming
 
Python tuple
Python   tuplePython   tuple
Python tuple
 
oops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaoops concept in java | object oriented programming in java
oops concept in java | object oriented programming in java
 
C++ OOPS Concept
C++ OOPS ConceptC++ OOPS Concept
C++ OOPS Concept
 
Strings in python
Strings in pythonStrings in python
Strings in python
 
Object Oriented Programming Using C++
Object Oriented Programming Using C++Object Oriented Programming Using C++
Object Oriented Programming Using C++
 
Python exception handling
Python   exception handlingPython   exception handling
Python exception handling
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++
 
Python-Inheritance.pptx
Python-Inheritance.pptxPython-Inheritance.pptx
Python-Inheritance.pptx
 
Static Data Members and Member Functions
Static Data Members and Member FunctionsStatic Data Members and Member Functions
Static Data Members and Member Functions
 
Command line arguments
Command line argumentsCommand line arguments
Command line arguments
 
OOP java
OOP javaOOP java
OOP java
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
 
File handling in Python
File handling in PythonFile handling in Python
File handling in Python
 
Data Structures in Python
Data Structures in PythonData Structures in Python
Data Structures in Python
 

Viewers also liked

Python 2 vs. Python 3
Python 2 vs. Python 3Python 2 vs. Python 3
Python 2 vs. Python 3
Pablo Enfedaque
 
Advance OOP concepts in Python
Advance OOP concepts in PythonAdvance OOP concepts in Python
Advance OOP concepts in Python
Sujith Kumar
 
Python Tricks That You Can't Live Without
Python Tricks That You Can't Live WithoutPython Tricks That You Can't Live Without
Python Tricks That You Can't Live Without
Audrey Roy
 
Python 2-基本語法
Python 2-基本語法Python 2-基本語法
Python 2-基本語法
阿Samn的物理課本
 
Introduction to Python
Introduction to Python Introduction to Python
Introduction to Python
amiable_indian
 
Python的50道陰影
Python的50道陰影Python的50道陰影
Python的50道陰影
Tim (文昌)
 
連淡水阿嬤都聽得懂的 機器學習入門 scikit-learn
連淡水阿嬤都聽得懂的機器學習入門 scikit-learn 連淡水阿嬤都聽得懂的機器學習入門 scikit-learn
連淡水阿嬤都聽得懂的 機器學習入門 scikit-learn
Cicilia Lee
 
常用內建模組
常用內建模組常用內建模組
常用內建模組
Justin Lin
 
型態與運算子
型態與運算子型態與運算子
型態與運算子
Justin Lin
 
進階主題
進階主題進階主題
進階主題
Justin Lin
 
Python 起步走
Python 起步走Python 起步走
Python 起步走
Justin Lin
 
Learn 90% of Python in 90 Minutes
Learn 90% of Python in 90 MinutesLearn 90% of Python in 90 Minutes
Learn 90% of Python in 90 Minutes
Matt Harrison
 
[系列活動] Python 程式語言起步走
[系列活動] Python 程式語言起步走[系列活動] Python 程式語言起步走
[系列活動] Python 程式語言起步走
台灣資料科學年會
 
[系列活動] Python爬蟲實戰
[系列活動] Python爬蟲實戰[系列活動] Python爬蟲實戰
[系列活動] Python爬蟲實戰
台灣資料科學年會
 
[系列活動] 無所不在的自然語言處理—基礎概念、技術與工具介紹
[系列活動] 無所不在的自然語言處理—基礎概念、技術與工具介紹[系列活動] 無所不在的自然語言處理—基礎概念、技術與工具介紹
[系列活動] 無所不在的自然語言處理—基礎概念、技術與工具介紹
台灣資料科學年會
 

Viewers also liked (15)

Python 2 vs. Python 3
Python 2 vs. Python 3Python 2 vs. Python 3
Python 2 vs. Python 3
 
Advance OOP concepts in Python
Advance OOP concepts in PythonAdvance OOP concepts in Python
Advance OOP concepts in Python
 
Python Tricks That You Can't Live Without
Python Tricks That You Can't Live WithoutPython Tricks That You Can't Live Without
Python Tricks That You Can't Live Without
 
Python 2-基本語法
Python 2-基本語法Python 2-基本語法
Python 2-基本語法
 
Introduction to Python
Introduction to Python Introduction to Python
Introduction to Python
 
Python的50道陰影
Python的50道陰影Python的50道陰影
Python的50道陰影
 
連淡水阿嬤都聽得懂的 機器學習入門 scikit-learn
連淡水阿嬤都聽得懂的機器學習入門 scikit-learn 連淡水阿嬤都聽得懂的機器學習入門 scikit-learn
連淡水阿嬤都聽得懂的 機器學習入門 scikit-learn
 
常用內建模組
常用內建模組常用內建模組
常用內建模組
 
型態與運算子
型態與運算子型態與運算子
型態與運算子
 
進階主題
進階主題進階主題
進階主題
 
Python 起步走
Python 起步走Python 起步走
Python 起步走
 
Learn 90% of Python in 90 Minutes
Learn 90% of Python in 90 MinutesLearn 90% of Python in 90 Minutes
Learn 90% of Python in 90 Minutes
 
[系列活動] Python 程式語言起步走
[系列活動] Python 程式語言起步走[系列活動] Python 程式語言起步走
[系列活動] Python 程式語言起步走
 
[系列活動] Python爬蟲實戰
[系列活動] Python爬蟲實戰[系列活動] Python爬蟲實戰
[系列活動] Python爬蟲實戰
 
[系列活動] 無所不在的自然語言處理—基礎概念、技術與工具介紹
[系列活動] 無所不在的自然語言處理—基礎概念、技術與工具介紹[系列活動] 無所不在的自然語言處理—基礎概念、技術與工具介紹
[系列活動] 無所不在的自然語言處理—基礎概念、技術與工具介紹
 

Similar to Basics of Object Oriented Programming in Python

Php oop (1)
Php oop (1)Php oop (1)
Php oop (1)
Sudip Simkhada
 
OOP interview questions & answers.
OOP interview questions & answers.OOP interview questions & answers.
OOP interview questions & answers.
Questpond
 
OOP in Java Presentation.pptx
OOP in Java Presentation.pptxOOP in Java Presentation.pptx
OOP in Java Presentation.pptx
mrxyz19
 
Object Oriented Javascript part2
Object Oriented Javascript part2Object Oriented Javascript part2
Object Oriented Javascript part2
Usman Mehmood
 
Selenium Training .pptx
Selenium Training .pptxSelenium Training .pptx
Selenium Training .pptx
SajidTk2
 
Synapseindia strcture of dotnet development part 1
Synapseindia strcture of dotnet development part 1Synapseindia strcture of dotnet development part 1
Synapseindia strcture of dotnet development part 1
Synapseindiappsdevelopment
 
Object-Oriented Programming in Java.pdf
Object-Oriented Programming in Java.pdfObject-Oriented Programming in Java.pdf
Object-Oriented Programming in Java.pdf
Bharath Choudhary
 
FAL(2022-23)_CSE0206_ETH_AP2022232000455_Reference_Material_I_16-Aug-2022_Mod...
FAL(2022-23)_CSE0206_ETH_AP2022232000455_Reference_Material_I_16-Aug-2022_Mod...FAL(2022-23)_CSE0206_ETH_AP2022232000455_Reference_Material_I_16-Aug-2022_Mod...
FAL(2022-23)_CSE0206_ETH_AP2022232000455_Reference_Material_I_16-Aug-2022_Mod...
AnkurSingh340457
 
python.pptx
python.pptxpython.pptx
python.pptx
Dhanushrajucm
 
Oops concepts
Oops conceptsOops concepts
Oops concepts
ACCESS Health Digital
 
Opp concept in c++
Opp concept in c++Opp concept in c++
Opp concept in c++
SadiqullahGhani1
 
4 pillars of OOPS CONCEPT
4 pillars of OOPS CONCEPT4 pillars of OOPS CONCEPT
4 pillars of OOPS CONCEPT
Ajay Chimmani
 
Object oriented basics
Object oriented basicsObject oriented basics
Object oriented basicsvamshimahi
 
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
Sagar Verma
 
Beginners Guide to Object Orientation in PHP
Beginners Guide to Object Orientation in PHPBeginners Guide to Object Orientation in PHP
Beginners Guide to Object Orientation in PHP
Rick Ogden
 
Java interview questions and answers
Java interview questions and answersJava interview questions and answers
Java interview questions and answers
Krishnaov
 
Oop.concepts
Oop.conceptsOop.concepts
Oop.concepts
tahir266
 
Object oriented javascript
Object oriented javascriptObject oriented javascript
Object oriented javascript
Usman Mehmood
 

Similar to Basics of Object Oriented Programming in Python (20)

Php oop (1)
Php oop (1)Php oop (1)
Php oop (1)
 
OOP interview questions & answers.
OOP interview questions & answers.OOP interview questions & answers.
OOP interview questions & answers.
 
OOP in Java Presentation.pptx
OOP in Java Presentation.pptxOOP in Java Presentation.pptx
OOP in Java Presentation.pptx
 
Object Oriented Javascript part2
Object Oriented Javascript part2Object Oriented Javascript part2
Object Oriented Javascript part2
 
Selenium Training .pptx
Selenium Training .pptxSelenium Training .pptx
Selenium Training .pptx
 
Synapseindia strcture of dotnet development part 1
Synapseindia strcture of dotnet development part 1Synapseindia strcture of dotnet development part 1
Synapseindia strcture of dotnet development part 1
 
Object-Oriented Programming in Java.pdf
Object-Oriented Programming in Java.pdfObject-Oriented Programming in Java.pdf
Object-Oriented Programming in Java.pdf
 
My c++
My c++My c++
My c++
 
FAL(2022-23)_CSE0206_ETH_AP2022232000455_Reference_Material_I_16-Aug-2022_Mod...
FAL(2022-23)_CSE0206_ETH_AP2022232000455_Reference_Material_I_16-Aug-2022_Mod...FAL(2022-23)_CSE0206_ETH_AP2022232000455_Reference_Material_I_16-Aug-2022_Mod...
FAL(2022-23)_CSE0206_ETH_AP2022232000455_Reference_Material_I_16-Aug-2022_Mod...
 
python.pptx
python.pptxpython.pptx
python.pptx
 
Oops concepts
Oops conceptsOops concepts
Oops concepts
 
Opp concept in c++
Opp concept in c++Opp concept in c++
Opp concept in c++
 
4 pillars of OOPS CONCEPT
4 pillars of OOPS CONCEPT4 pillars of OOPS CONCEPT
4 pillars of OOPS CONCEPT
 
Object oriented basics
Object oriented basicsObject oriented basics
Object oriented basics
 
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
 
Oops
OopsOops
Oops
 
Beginners Guide to Object Orientation in PHP
Beginners Guide to Object Orientation in PHPBeginners Guide to Object Orientation in PHP
Beginners Guide to Object Orientation in PHP
 
Java interview questions and answers
Java interview questions and answersJava interview questions and answers
Java interview questions and answers
 
Oop.concepts
Oop.conceptsOop.concepts
Oop.concepts
 
Object oriented javascript
Object oriented javascriptObject oriented javascript
Object oriented javascript
 

Recently uploaded

When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
Elena Simperl
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
Generating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using SmithyGenerating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using Smithy
g2nightmarescribd
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Ramesh Iyer
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Sri Ambati
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
OnBoard
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Inflectra
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
DianaGray10
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Albert Hoitingh
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Jeffrey Haguewood
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
ControlCase
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
Paul Groth
 

Recently uploaded (20)

When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
Generating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using SmithyGenerating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using Smithy
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 

Basics of 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/26/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/26/2014 VYBHAVA TECHNOLOGIES 3
  • 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/26/2014 VYBHAVA TECHNOLOGIES 4
  • 5. Fundamental concepts of OOP in Python The four major principles of object orientation are: Encapsulation Data Abstraction Inheritance Polymorphism 7/26/2014 VYBHAVA TECHNOLOGIES 5
  • 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/26/2014 VYBHAVA TECHNOLOGIES 6
  • 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/26/2014 VYBHAVA TECHNOLOGIES 7
  • 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/26/2014 VYBHAVA TECHNOLOGIES 8
  • 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/26/2014 VYBHAVA TECHNOLOGIES 9
  • 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/26/2014 VYBHAVA TECHNOLOGIES 10
  • 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/26/2014 VYBHAVA TECHNOLOGIES 11
  • 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/26/2014 VYBHAVA TECHNOLOGIES 12
  • 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/26/2014 VYBHAVA TECHNOLOGIES 13
  • 14. Deleting instances: No Need to “free” 7/26/2014 VYBHAVA TECHNOLOGIES 14  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
  • 15. Syntax for accessing attributes and methods >>> f = student(“Python”, 14) >>> f.full_name # Access attribute “Python” >>> f.get_age() # Access a method 14 7/26/2014 VYBHAVA TECHNOLOGIES 15
  • 16. 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/26/2014 VYBHAVA TECHNOLOGIES 16
  • 17.  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/26/2014 VYBHAVA TECHNOLOGIES 17
  • 18. Public, Protected and Private Data 7/26/2014 VYBHAVA TECHNOLOGIES 18  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
  • 19.  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/26/2014 VYBHAVA TECHNOLOGIES 19
  • 20. 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/26/2014 VYBHAVA TECHNOLOGIES 20
  • 21. The following table shows the different behavior Public, Protected and Private Data 7/26/2014 VYBHAVA TECHNOLOGIES 21 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
  • 22. 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/26/2014 VYBHAVA TECHNOLOGIES 22
  • 23. 7/26/2014 VYBHAVA TECHNOLOGIES 23 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.
  • 24. 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/26/2014 VYBHAVA TECHNOLOGIES 24
  • 25. 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/26/2014 VYBHAVA TECHNOLOGIES 25
  • 26. A simple word ‘Cut’ can have different meaning depending where it is used 7/26/2014 VYBHAVA TECHNOLOGIES 26 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
  • 27. 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/26/2014 VYBHAVA TECHNOLOGIES 27
  • 28. 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/26/2014 VYBHAVA TECHNOLOGIES 28 Operator Overloading
  • 29. 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/26/2014 VYBHAVA TECHNOLOGIES 29 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)

Editor's Notes

  1. Need improve difference between protected vs public/private