SlideShare a Scribd company logo
1 of 47
Date:30/01/2015
pinjut@gmail.com
sanooja jabbar t.com/baabtra
twitter.com/baabtra
in.linkedin.com/in/baabtra
OOPs in
Object Oriented Programming
❖ Python is an object-oriented programming language.
❖ Python doesn't force to use the object-oriented paradigm
exclusively.
❖ Python also supports procedural programming with
modules and functions, so you can select the most suitable
programming paradigm for each part of your program.
“Generally, the object-oriented paradigm is suitable when you want to
group state (data) and behavior (code) together in handy packets of
functionality.”
objects
a software item that contains
variables and methods
❖ 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)
classes
binds the member variables and
methods
into a single unit
Syntax:
class classname:
statement(s)
Example:
class myClass:
def hello(self):
print "Hello"
def sum(self):
int_res=100+200
return int_res
Creating Instance Objects
Syntax
anInstance=class_name()
Example
classObj=myClass()
Accessing Attributes
Example:
classObj.hello()
int_sum=classObj.sum()
print “The sum is : ”,int_sum
output:
Hello
The sum is : 300
Object Oriented Design focuses on
➔ Encapsulation:
dividing the code into a public interface, and a private
implementation of that interface
➔ Polymorphism:
the ability to overload standard operators so that they have
appropriate behavior based on their context
➔ Inheritance:
the ability to create subclasses that contain specializations
of their parents
inheritance
child class acquires the
properties of the parent
class
➔ Simple Inheritance
Syntax
derived_class(base_class)
➔ Multiple Inheritance
Syntax
derived_class(base_class[,base_class1][,base_class2
][....])
Example for Simple Inheritance:
class myClass:
def sum(self):
int_res=100+200
return int_res
class newClass(myClass):
def hello(self):
print "Maya"
classObj=newClass()
classObj.hello()
int_sum=classObj.sum()
print “The sum is : ”,int_sum
output:
Maya
The sum is : 300
Example for Multiple inheritance
class A:
def displayA(self):
print "Class A"
class B:
def displayB(self):
print "Class B"
class c(A,B):
def displayC(self):
print "Class C"
objC=c()
objC.displayA()
objC.displayB()
objC.displayC()
Output:
Class A
Class B
Class C
polymorphis
m
process of using an operator
❖ Uses polymorphism extensively in built-in types.
❖ Here we use the same indexing operator for three different
data types.
❖ Polymorphism is most commonly used when dealing with
inheritance.
❖ Example:
a = "alfa" # string
b = (1, 2, 3, 4) # tuple
c = ['o', 'm', 'e', 'g', 'a'] # list
print a[2]
print b[1]
print c[3]
Output:
f
2
g
Two kinds of Polymorphism:
❖ Overloading
- Two or more methods with different signatures
- Python operators works for built-in Classes
❖ Overriding
- Replacing an inherited method with another having the
same signature
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)
Explanation for Operator Overloading Sample Program
What actually happens is that, when you do p1 - p2, Python will
call p1.__sub__(p2). Similarly, we can overload other operators
as well. The special function that we need to implement is
tabulated below
Example for Overriding
class Animal:
def __init__(self, name=''):
self.name = name
def talk(self):
pass
class Cat(Animal):
def talk(self):
print "Meow!"
class Dog(Animal):
def talk(self):
print "Woof!"
a = Animal()
a.talk()
c = Cat("Missy")
c.talk()
d = Dog("Rocky")
d.talk()
Output:
Meow!
Woof!
encapsulatio
n
process of binding data members and
member functions into a single unit
❖ An important concept in OOP
❖ Data Abstraction is achieved through Encapsulation
❖ Generally speaking encapsulation is the mechanism for
restricting the access to some of an object's components, this
means, that the internal representation of an object can't be
seen from outside of the objects definition.
Name Notation Behaviour
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
The following table shows the different behaviour of Public,
Protected and Private Data
Example for Public, Private and Protected Data
>>> class Encapsulation():
def __init__(self,a,b,c):
self.public=a
self._protected=b
self.__private=c
>>> 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 "<pyshell#12>", line 1, in <module>
x.private
AttributeError: 'Encapsulation' object has no attribute '__private'
>>>
special
methods
classes in python can implement
certain operations with special
method names.
❖ They are also called “Magic Methods”
❖ They are not called directly, but by a specific language
syntax
❖ This is similar to what is known as operator overloading in
C++
❖ Contains clumsy syntax, ie., double underscore at the
beginning and end
❖ So simplicity __init__() can be read as “dunder init
dunder”
❖ So magic methods also called “Dunder Methods”
Some special methods are:
1) __init__()
default constructor, when an instance of class is created
2) __str__()
If we print an object then its __str__() method will get
called
3) __len__()
Returns the length of the container
4) __del__()
It destructs the constructors that have created using
__init__()
Example for Special Methods
class Book:
def __init__(self, title, author, pages):
print "A book is created"
self.title = title
self.author = author
self.pages = pages
def __str__(self):
return "Title:%s , author:%s, pages:%s " % 
(self.title, self.author, self.pages)
def __len__(self):
return self.pages
def __del__(self):
print "A book is destroyed"
book = Book("Inside Steve's Brain", "Leander Kahney", 304)
print book
print len(book)
del book Output:
A book is created
Title:Inside Steve's Brain , author:Leander Kahney, pages:304
304
A book is destroyed
class Book:
def __init__(self, title, author, pages):
print "A book is created"
self.title = title
self.author = author
self.pages = pages
def __str__(self):
return "Title:%s , author:%s, pages:%s " % 
(self.title, self.author, self.pages)
def __len__(self):
return self.pages
def __del__(self):
print "A book is destroyed"
book = Book("Inside Steve's Brain", "Leander Kahney",
304)
print book
print len(book)
del book
Output:
A book is created
Here we call the __init__() method. The
method creates a new instance of a Book
class.
class Book:
def __init__(self, title, author, pages):
print "A book is created"
self.title = title
self.author = author
self.pages = pages
def __str__(self):
return "Title:%s , author:%s, pages:%s " % 
(self.title, self.author, self.pages)
def __len__(self):
return self.pages
def __del__(self):
print "A book is destroyed"
book = Book("Inside Steve's Brain", "Leander Kahney", 304)
print book
print len(book)
del book
Output:
A book is created
Title:Inside Steve's Brain ,
author:Leander Kahney, pages:304
The print keyword calls the __str__() method.
This method should return an informal string
representation of an object.
class Book:
def __init__(self, title, author, pages):
print "A book is created"
self.title = title
self.author = author
self.pages = pages
def __str__(self):
return "Title:%s , author:%s, pages:%s " % 
(self.title, self.author, self.pages)
def __len__(self):
return self.pages
def __del__(self):
print "A book is destroyed"
book = Book("Inside Steve's Brain", "Leander Kahney", 304)
print book
print len(book)
del book
Output:
A book is created
Title:Inside Steve's Brain ,
author:Leander Kahney, pages:304
304
The len() function invokes the __len__()
method. In our case, we print the number of
pages of your book.
class Book:
def __init__(self, title, author, pages):
print "A book is created"
self.title = title
self.author = author
self.pages = pages
def __str__(self):
return "Title:%s , author:%s, pages:%s " % 
(self.title, self.author, self.pages)
def __len__(self):
return self.pages
def __del__(self):
print "A book is destroyed"
book = Book("Inside Steve's Brain", "Leander Kahney", 304)
print book
print len(book)
del book
Output:
A book is created
Title:Inside Steve's Brain ,
author:Leander Kahney, pages:304
304
A book is destroyed
The del keyword deletes an object. It calls the
__del__() method.
modules
using import statement
❖ A typical Python program is made up of several source files.
Each source file corresponds to a module, which packages
program code and data for reuse.
❖ Modules are normally independent of each other so that other
programs can reuse the specific modules they need.
❖ A module explicitly establishes dependencies upon another
module by using import statements.
Import Statement
Syntax
import modname [as varname][,...]
Example
import MyModule1
import MyModule as Alias
Import Statement
Syntax
import modname [as varname][,...]
Example
import MyModule1
import MyModule as Alias
In the simplest and most
common case, modname is an
identifier, the name of a
variable that Python binds to
the module object when the
import statement finishes
Import Statement
Syntax
import modname [as varname][,...]
Example
import MyModule1
import MyModule as Alias
looks for the module named
MyModule and binds the
variable named Alias in the
current scope to the module
object. varname is always a
simple identifier.
Relative Import Statement
Suppose we are here and we want to
import the file employeeDetails.py
which resides in a directory as shown
Relative Import Statement
import sys
import os
str_current_path = os.getcwd() ## get current working directory
str_module_path = str_current_path.replace( ' Accounts',‘HR/employees /
')
sys.path.append( str_module_path )
import employeeDetails
➔ sys.path
A list of strings that specifies the search path for modules
➔ sys.path.append( module path )
This statement append our module path with the existing list
of sys.path, then the import statement search for the module in
the module path as we specified.
Relative Import Statement
❖ When the Python interpreter reads a source file, it executes all of
the code found in it. But Before executing the code, it will define a
few special variables.
❖ For example, if the python interpreter is running a module (the
source file) as the main program, it sets the special __name__
variable to have a value"__main__".
❖ If this file is being imported from another module, __name__ will
be set to the module's name.
__main__()
def func():
print("func() in one.py")
print("top-level in one.py")
if __name__ == "__main__":
print("one.py is being run
directly")
else:
print("one.py is being
imported into another module")
# File one.py # File two.py
import one
print("top-level in two.py")
one.func()
if __name__ == "__main__":
print("two.py is being run
directly")
else:
print("two.py is being
imported into another module")
Example
def func():
print("func() in one.py")
print("top-level in one.py")
if __name__ == "__main__":
print("one.py is being run
directly")
else:
print("one.py is being
imported into another module")
# File one.py # File two.py
import one
print("top-level in two.py")
one.func()
if __name__ == "__main__":
print("two.py is being run
directly")
else:
print("two.py is being
imported into another module")
Example
When we run one.py
---------------------------
Top-level in one.py
One.py is being run directly
def func():
print("func() in one.py")
print("top-level in one.py")
if __name__ == "__main__":
print("one.py is being run
directly")
else:
print("one.py is being
imported into another module")
# File one.py # File two.py
import one
print("top-level in two.py")
one.func()
if __name__ == "__main__":
print("two.py is being run
directly")
else:
print("two.py is being
imported into another module")
Example
When we run two.py
-----------------------------
top-level in one.py
one.py is being imported into another module
top-level in two.py
func() in one.py
two.py is being run directly
US UK UAE
7002 Hana Road,
Edison NJ 08817,
United States of America.
90 High Street,
Cherry Hinton,
Cambridge, CB1 9HZ,
United Kingdom.
Suite No: 51, Oasis Center,
Sheikh Zayed Road, Dubai,
UAE
Email to info@baabtra.com or Visit baabtra.com
Looking for learning more about the above
topic?
India Centres
Emarald Mall (Big Bazar Building)
Mavoor Road, Kozhikode,
Kerala, India.
Ph: + 91 – 495 40 25 550
NC Complex, Near Bus Stand
Mukkam, Kozhikode,
Kerala, India.
Ph: + 91 – 495 40 25 550
Cafit Square IT Park,
Hilite Business Park,
Kozhikode
Kerala, India.
Email: info@baabtra.com
TBI - NITC
NIT Campus, Kozhikode.
Kerala, India.
Start up Village
Eranakulam,
Kerala, India.
Start up Village
UL CC
Kozhikode, Kerala
Follow us @ twitter.com/baabtra
Like us @ facebook.com/baabtra
Subscribe to us @ youtube.com/baabtra
Become a follower @ slideshare.net/BaabtraMentoringPartner
Connect to us @ in.linkedin.com/in/baabtra
Give a feedback @ massbaab.com/baabtra
Thanks in advance
www.baabtra.com | www.massbaab.com |www.baabte.com
Want to learn more about programming or Looking to become a good programmer?
Are you wasting time on searching so many contents online?
Do you want to learn things quickly?
Tired of spending huge amount of money to become a Software professional?
Do an online course
@ baabtra.com
We put industry standards to practice. Our structured, activity based courses are so designed
to make a quick, good software professional out of anybody who holds a passion for coding.

More Related Content

What's hot

Conditional and control statement
Conditional and control statementConditional and control statement
Conditional and control statementnarmadhakin
 
File handling in Python
File handling in PythonFile handling in Python
File handling in PythonMegha V
 
Data Structures in Python
Data Structures in PythonData Structures in Python
Data Structures in PythonDevashish Kumar
 
JavaScript - Chapter 12 - Document Object Model
  JavaScript - Chapter 12 - Document Object Model  JavaScript - Chapter 12 - Document Object Model
JavaScript - Chapter 12 - Document Object ModelWebStackAcademy
 
Data types in python
Data types in pythonData types in python
Data types in pythonRaginiJain21
 
Class, object and inheritance in python
Class, object and inheritance in pythonClass, object and inheritance in python
Class, object and inheritance in pythonSantosh Verma
 
Class and Objects in Java
Class and Objects in JavaClass and Objects in Java
Class and Objects in JavaSpotle.ai
 
Values and Data types in python
Values and Data types in pythonValues and Data types in python
Values and Data types in pythonJothi Thilaga P
 
Python Generators
Python GeneratorsPython Generators
Python GeneratorsAkshar Raaj
 
Regular expressions in Python
Regular expressions in PythonRegular expressions in Python
Regular expressions in PythonSujith Kumar
 
Advance OOP concepts in Python
Advance OOP concepts in PythonAdvance OOP concepts in Python
Advance OOP concepts in PythonSujith Kumar
 
Introduction to python programming
Introduction to python programmingIntroduction to python programming
Introduction to python programmingSrinivas Narasegouda
 
Dom(document object model)
Dom(document object model)Dom(document object model)
Dom(document object model)Partnered Health
 
Procedural vs. object oriented programming
Procedural vs. object oriented programmingProcedural vs. object oriented programming
Procedural vs. object oriented programmingHaris Bin Zahid
 

What's hot (20)

Conditional and control statement
Conditional and control statementConditional and control statement
Conditional and control statement
 
File handling in Python
File handling in PythonFile handling in Python
File handling in Python
 
Python : Functions
Python : FunctionsPython : Functions
Python : Functions
 
Object oriented programming in python
Object oriented programming in pythonObject oriented programming in python
Object oriented programming in python
 
Data Structures in Python
Data Structures in PythonData Structures in Python
Data Structures in Python
 
JavaScript - Chapter 12 - Document Object Model
  JavaScript - Chapter 12 - Document Object Model  JavaScript - Chapter 12 - Document Object Model
JavaScript - Chapter 12 - Document Object Model
 
Data types in python
Data types in pythonData types in python
Data types in python
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
 
Class, object and inheritance in python
Class, object and inheritance in pythonClass, object and inheritance in python
Class, object and inheritance in python
 
Class and Objects in Java
Class and Objects in JavaClass and Objects in Java
Class and Objects in Java
 
Values and Data types in python
Values and Data types in pythonValues and Data types in python
Values and Data types in python
 
Python exception handling
Python   exception handlingPython   exception handling
Python exception handling
 
Python Generators
Python GeneratorsPython Generators
Python Generators
 
Database programming
Database programmingDatabase programming
Database programming
 
Regular expressions in Python
Regular expressions in PythonRegular expressions in Python
Regular expressions in Python
 
Advance OOP concepts in Python
Advance OOP concepts in PythonAdvance OOP concepts in Python
Advance OOP concepts in Python
 
Python Functions
Python   FunctionsPython   Functions
Python Functions
 
Introduction to python programming
Introduction to python programmingIntroduction to python programming
Introduction to python programming
 
Dom(document object model)
Dom(document object model)Dom(document object model)
Dom(document object model)
 
Procedural vs. object oriented programming
Procedural vs. object oriented programmingProcedural vs. object oriented programming
Procedural vs. object oriented programming
 

Similar to Oop concepts in python

جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲Mohammad Reza Kamalifard
 
Introduction to Python - Part Three
Introduction to Python - Part ThreeIntroduction to Python - Part Three
Introduction to Python - Part Threeamiable_indian
 
Python introduction 2
Python introduction 2Python introduction 2
Python introduction 2Ahmad Hussein
 
Chap 3 Python Object Oriented Programming - Copy.ppt
Chap 3 Python Object Oriented Programming - Copy.pptChap 3 Python Object Oriented Programming - Copy.ppt
Chap 3 Python Object Oriented Programming - Copy.pptmuneshwarbisen1
 
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdfPython Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdfSudhanshiBakre1
 
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdfPython Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdfSudhanshiBakre1
 
Class 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented ProgrammingClass 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented ProgrammingAhmed Swilam
 
Slides python elixir
Slides python elixirSlides python elixir
Slides python elixirAdel Totott
 
Lotusphere 2007 BP301 Advanced Object Oriented Programming for LotusScript
Lotusphere 2007 BP301 Advanced Object Oriented Programming for LotusScriptLotusphere 2007 BP301 Advanced Object Oriented Programming for LotusScript
Lotusphere 2007 BP301 Advanced Object Oriented Programming for LotusScriptBill Buchan
 
Ejb3 Struts Tutorial En
Ejb3 Struts Tutorial EnEjb3 Struts Tutorial En
Ejb3 Struts Tutorial EnAnkur Dongre
 
Ejb3 Struts Tutorial En
Ejb3 Struts Tutorial EnEjb3 Struts Tutorial En
Ejb3 Struts Tutorial EnAnkur Dongre
 
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونیاسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونیMohammad Reza Kamalifard
 
These questions will be a bit advanced level 2
These questions will be a bit advanced level 2These questions will be a bit advanced level 2
These questions will be a bit advanced level 2sadhana312471
 
Presentation 3rd
Presentation 3rdPresentation 3rd
Presentation 3rdConnex
 

Similar to Oop concepts in python (20)

Python classes objects
Python classes objectsPython classes objects
Python classes objects
 
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
 
Introduction to Python - Part Three
Introduction to Python - Part ThreeIntroduction to Python - Part Three
Introduction to Python - Part Three
 
Python advance
Python advancePython advance
Python advance
 
Spsl vi unit final
Spsl vi unit finalSpsl vi unit final
Spsl vi unit final
 
Spsl v unit - final
Spsl v unit - finalSpsl v unit - final
Spsl v unit - final
 
Python introduction 2
Python introduction 2Python introduction 2
Python introduction 2
 
Python_Unit_2 OOPS.pptx
Python_Unit_2  OOPS.pptxPython_Unit_2  OOPS.pptx
Python_Unit_2 OOPS.pptx
 
Chap 3 Python Object Oriented Programming - Copy.ppt
Chap 3 Python Object Oriented Programming - Copy.pptChap 3 Python Object Oriented Programming - Copy.ppt
Chap 3 Python Object Oriented Programming - Copy.ppt
 
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdfPython Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
 
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdfPython Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
 
Class 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented ProgrammingClass 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented Programming
 
Slides python elixir
Slides python elixirSlides python elixir
Slides python elixir
 
Lotusphere 2007 BP301 Advanced Object Oriented Programming for LotusScript
Lotusphere 2007 BP301 Advanced Object Oriented Programming for LotusScriptLotusphere 2007 BP301 Advanced Object Oriented Programming for LotusScript
Lotusphere 2007 BP301 Advanced Object Oriented Programming for LotusScript
 
Unit - 3.pptx
Unit - 3.pptxUnit - 3.pptx
Unit - 3.pptx
 
Ejb3 Struts Tutorial En
Ejb3 Struts Tutorial EnEjb3 Struts Tutorial En
Ejb3 Struts Tutorial En
 
Ejb3 Struts Tutorial En
Ejb3 Struts Tutorial EnEjb3 Struts Tutorial En
Ejb3 Struts Tutorial En
 
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونیاسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
 
These questions will be a bit advanced level 2
These questions will be a bit advanced level 2These questions will be a bit advanced level 2
These questions will be a bit advanced level 2
 
Presentation 3rd
Presentation 3rdPresentation 3rd
Presentation 3rd
 

More from baabtra.com - No. 1 supplier of quality freshers

More from baabtra.com - No. 1 supplier of quality freshers (20)

Agile methodology and scrum development
Agile methodology and scrum developmentAgile methodology and scrum development
Agile methodology and scrum development
 
Best coding practices
Best coding practicesBest coding practices
Best coding practices
 
Core java - baabtra
Core java - baabtraCore java - baabtra
Core java - baabtra
 
Acquiring new skills what you should know
Acquiring new skills   what you should knowAcquiring new skills   what you should know
Acquiring new skills what you should know
 
Baabtra.com programming at school
Baabtra.com programming at schoolBaabtra.com programming at school
Baabtra.com programming at school
 
99LMS for Enterprises - LMS that you will love
99LMS for Enterprises - LMS that you will love 99LMS for Enterprises - LMS that you will love
99LMS for Enterprises - LMS that you will love
 
Php sessions & cookies
Php sessions & cookiesPhp sessions & cookies
Php sessions & cookies
 
Php database connectivity
Php database connectivityPhp database connectivity
Php database connectivity
 
Chapter 6 database normalisation
Chapter 6  database normalisationChapter 6  database normalisation
Chapter 6 database normalisation
 
Chapter 5 transactions and dcl statements
Chapter 5  transactions and dcl statementsChapter 5  transactions and dcl statements
Chapter 5 transactions and dcl statements
 
Chapter 4 functions, views, indexing
Chapter 4  functions, views, indexingChapter 4  functions, views, indexing
Chapter 4 functions, views, indexing
 
Chapter 3 stored procedures
Chapter 3 stored proceduresChapter 3 stored procedures
Chapter 3 stored procedures
 
Chapter 2 grouping,scalar and aggergate functions,joins inner join,outer join
Chapter 2  grouping,scalar and aggergate functions,joins   inner join,outer joinChapter 2  grouping,scalar and aggergate functions,joins   inner join,outer join
Chapter 2 grouping,scalar and aggergate functions,joins inner join,outer join
 
Chapter 1 introduction to sql server
Chapter 1 introduction to sql serverChapter 1 introduction to sql server
Chapter 1 introduction to sql server
 
Chapter 1 introduction to sql server
Chapter 1 introduction to sql serverChapter 1 introduction to sql server
Chapter 1 introduction to sql server
 
Microsoft holo lens
Microsoft holo lensMicrosoft holo lens
Microsoft holo lens
 
Blue brain
Blue brainBlue brain
Blue brain
 
5g
5g5g
5g
 
Aptitude skills baabtra
Aptitude skills baabtraAptitude skills baabtra
Aptitude skills baabtra
 
Gd baabtra
Gd baabtraGd baabtra
Gd baabtra
 

Recently uploaded

SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfUmakantAnnand
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxRoyAbrique
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991RKavithamani
 

Recently uploaded (20)

SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.Compdf
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
 

Oop concepts in python

  • 1.
  • 3. Object Oriented Programming ❖ Python is an object-oriented programming language. ❖ Python doesn't force to use the object-oriented paradigm exclusively. ❖ Python also supports procedural programming with modules and functions, so you can select the most suitable programming paradigm for each part of your program. “Generally, the object-oriented paradigm is suitable when you want to group state (data) and behavior (code) together in handy packets of functionality.”
  • 4. objects a software item that contains variables and methods
  • 5. ❖ 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)
  • 6. classes binds the member variables and methods into a single unit
  • 7. Syntax: class classname: statement(s) Example: class myClass: def hello(self): print "Hello" def sum(self): int_res=100+200 return int_res
  • 10. Object Oriented Design focuses on ➔ Encapsulation: dividing the code into a public interface, and a private implementation of that interface ➔ Polymorphism: the ability to overload standard operators so that they have appropriate behavior based on their context ➔ Inheritance: the ability to create subclasses that contain specializations of their parents
  • 11. inheritance child class acquires the properties of the parent class
  • 12. ➔ Simple Inheritance Syntax derived_class(base_class) ➔ Multiple Inheritance Syntax derived_class(base_class[,base_class1][,base_class2 ][....])
  • 13. Example for Simple Inheritance: class myClass: def sum(self): int_res=100+200 return int_res class newClass(myClass): def hello(self): print "Maya" classObj=newClass() classObj.hello() int_sum=classObj.sum() print “The sum is : ”,int_sum output: Maya The sum is : 300
  • 14. Example for Multiple inheritance class A: def displayA(self): print "Class A" class B: def displayB(self): print "Class B" class c(A,B): def displayC(self): print "Class C" objC=c() objC.displayA() objC.displayB() objC.displayC() Output: Class A Class B Class C
  • 16. ❖ Uses polymorphism extensively in built-in types. ❖ Here we use the same indexing operator for three different data types. ❖ Polymorphism is most commonly used when dealing with inheritance. ❖ Example: a = "alfa" # string b = (1, 2, 3, 4) # tuple c = ['o', 'm', 'e', 'g', 'a'] # list print a[2] print b[1] print c[3] Output: f 2 g
  • 17. Two kinds of Polymorphism: ❖ Overloading - Two or more methods with different signatures - Python operators works for built-in Classes ❖ Overriding - Replacing an inherited method with another having the same signature
  • 18. 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) Explanation for Operator Overloading Sample Program What actually happens is that, when you do p1 - p2, Python will call p1.__sub__(p2). Similarly, we can overload other operators as well. The special function that we need to implement is tabulated below
  • 19. Example for Overriding class Animal: def __init__(self, name=''): self.name = name def talk(self): pass class Cat(Animal): def talk(self): print "Meow!" class Dog(Animal): def talk(self): print "Woof!" a = Animal() a.talk() c = Cat("Missy") c.talk() d = Dog("Rocky") d.talk() Output: Meow! Woof!
  • 20. encapsulatio n process of binding data members and member functions into a single unit
  • 21. ❖ An important concept in OOP ❖ Data Abstraction is achieved through Encapsulation ❖ Generally speaking encapsulation is the mechanism for restricting the access to some of an object's components, this means, that the internal representation of an object can't be seen from outside of the objects definition.
  • 22. Name Notation Behaviour 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 The following table shows the different behaviour of Public, Protected and Private Data
  • 23. Example for Public, Private and Protected Data >>> class Encapsulation(): def __init__(self,a,b,c): self.public=a self._protected=b self.__private=c >>> 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 "<pyshell#12>", line 1, in <module> x.private AttributeError: 'Encapsulation' object has no attribute '__private' >>>
  • 24. special methods classes in python can implement certain operations with special method names.
  • 25. ❖ They are also called “Magic Methods” ❖ They are not called directly, but by a specific language syntax ❖ This is similar to what is known as operator overloading in C++ ❖ Contains clumsy syntax, ie., double underscore at the beginning and end ❖ So simplicity __init__() can be read as “dunder init dunder” ❖ So magic methods also called “Dunder Methods”
  • 26. Some special methods are: 1) __init__() default constructor, when an instance of class is created 2) __str__() If we print an object then its __str__() method will get called 3) __len__() Returns the length of the container 4) __del__() It destructs the constructors that have created using __init__()
  • 27. Example for Special Methods class Book: def __init__(self, title, author, pages): print "A book is created" self.title = title self.author = author self.pages = pages def __str__(self): return "Title:%s , author:%s, pages:%s " % (self.title, self.author, self.pages) def __len__(self): return self.pages def __del__(self): print "A book is destroyed" book = Book("Inside Steve's Brain", "Leander Kahney", 304) print book print len(book) del book Output: A book is created Title:Inside Steve's Brain , author:Leander Kahney, pages:304 304 A book is destroyed
  • 28. class Book: def __init__(self, title, author, pages): print "A book is created" self.title = title self.author = author self.pages = pages def __str__(self): return "Title:%s , author:%s, pages:%s " % (self.title, self.author, self.pages) def __len__(self): return self.pages def __del__(self): print "A book is destroyed" book = Book("Inside Steve's Brain", "Leander Kahney", 304) print book print len(book) del book Output: A book is created Here we call the __init__() method. The method creates a new instance of a Book class.
  • 29. class Book: def __init__(self, title, author, pages): print "A book is created" self.title = title self.author = author self.pages = pages def __str__(self): return "Title:%s , author:%s, pages:%s " % (self.title, self.author, self.pages) def __len__(self): return self.pages def __del__(self): print "A book is destroyed" book = Book("Inside Steve's Brain", "Leander Kahney", 304) print book print len(book) del book Output: A book is created Title:Inside Steve's Brain , author:Leander Kahney, pages:304 The print keyword calls the __str__() method. This method should return an informal string representation of an object.
  • 30. class Book: def __init__(self, title, author, pages): print "A book is created" self.title = title self.author = author self.pages = pages def __str__(self): return "Title:%s , author:%s, pages:%s " % (self.title, self.author, self.pages) def __len__(self): return self.pages def __del__(self): print "A book is destroyed" book = Book("Inside Steve's Brain", "Leander Kahney", 304) print book print len(book) del book Output: A book is created Title:Inside Steve's Brain , author:Leander Kahney, pages:304 304 The len() function invokes the __len__() method. In our case, we print the number of pages of your book.
  • 31. class Book: def __init__(self, title, author, pages): print "A book is created" self.title = title self.author = author self.pages = pages def __str__(self): return "Title:%s , author:%s, pages:%s " % (self.title, self.author, self.pages) def __len__(self): return self.pages def __del__(self): print "A book is destroyed" book = Book("Inside Steve's Brain", "Leander Kahney", 304) print book print len(book) del book Output: A book is created Title:Inside Steve's Brain , author:Leander Kahney, pages:304 304 A book is destroyed The del keyword deletes an object. It calls the __del__() method.
  • 33. ❖ A typical Python program is made up of several source files. Each source file corresponds to a module, which packages program code and data for reuse. ❖ Modules are normally independent of each other so that other programs can reuse the specific modules they need. ❖ A module explicitly establishes dependencies upon another module by using import statements.
  • 34. Import Statement Syntax import modname [as varname][,...] Example import MyModule1 import MyModule as Alias
  • 35. Import Statement Syntax import modname [as varname][,...] Example import MyModule1 import MyModule as Alias In the simplest and most common case, modname is an identifier, the name of a variable that Python binds to the module object when the import statement finishes
  • 36. Import Statement Syntax import modname [as varname][,...] Example import MyModule1 import MyModule as Alias looks for the module named MyModule and binds the variable named Alias in the current scope to the module object. varname is always a simple identifier.
  • 37. Relative Import Statement Suppose we are here and we want to import the file employeeDetails.py which resides in a directory as shown
  • 38. Relative Import Statement import sys import os str_current_path = os.getcwd() ## get current working directory str_module_path = str_current_path.replace( ' Accounts',‘HR/employees / ') sys.path.append( str_module_path ) import employeeDetails
  • 39. ➔ sys.path A list of strings that specifies the search path for modules ➔ sys.path.append( module path ) This statement append our module path with the existing list of sys.path, then the import statement search for the module in the module path as we specified. Relative Import Statement
  • 40. ❖ When the Python interpreter reads a source file, it executes all of the code found in it. But Before executing the code, it will define a few special variables. ❖ For example, if the python interpreter is running a module (the source file) as the main program, it sets the special __name__ variable to have a value"__main__". ❖ If this file is being imported from another module, __name__ will be set to the module's name. __main__()
  • 41. def func(): print("func() in one.py") print("top-level in one.py") if __name__ == "__main__": print("one.py is being run directly") else: print("one.py is being imported into another module") # File one.py # File two.py import one print("top-level in two.py") one.func() if __name__ == "__main__": print("two.py is being run directly") else: print("two.py is being imported into another module") Example
  • 42. def func(): print("func() in one.py") print("top-level in one.py") if __name__ == "__main__": print("one.py is being run directly") else: print("one.py is being imported into another module") # File one.py # File two.py import one print("top-level in two.py") one.func() if __name__ == "__main__": print("two.py is being run directly") else: print("two.py is being imported into another module") Example When we run one.py --------------------------- Top-level in one.py One.py is being run directly
  • 43. def func(): print("func() in one.py") print("top-level in one.py") if __name__ == "__main__": print("one.py is being run directly") else: print("one.py is being imported into another module") # File one.py # File two.py import one print("top-level in two.py") one.func() if __name__ == "__main__": print("two.py is being run directly") else: print("two.py is being imported into another module") Example When we run two.py ----------------------------- top-level in one.py one.py is being imported into another module top-level in two.py func() in one.py two.py is being run directly
  • 44. US UK UAE 7002 Hana Road, Edison NJ 08817, United States of America. 90 High Street, Cherry Hinton, Cambridge, CB1 9HZ, United Kingdom. Suite No: 51, Oasis Center, Sheikh Zayed Road, Dubai, UAE Email to info@baabtra.com or Visit baabtra.com Looking for learning more about the above topic?
  • 45. India Centres Emarald Mall (Big Bazar Building) Mavoor Road, Kozhikode, Kerala, India. Ph: + 91 – 495 40 25 550 NC Complex, Near Bus Stand Mukkam, Kozhikode, Kerala, India. Ph: + 91 – 495 40 25 550 Cafit Square IT Park, Hilite Business Park, Kozhikode Kerala, India. Email: info@baabtra.com TBI - NITC NIT Campus, Kozhikode. Kerala, India. Start up Village Eranakulam, Kerala, India. Start up Village UL CC Kozhikode, Kerala
  • 46. Follow us @ twitter.com/baabtra Like us @ facebook.com/baabtra Subscribe to us @ youtube.com/baabtra Become a follower @ slideshare.net/BaabtraMentoringPartner Connect to us @ in.linkedin.com/in/baabtra Give a feedback @ massbaab.com/baabtra Thanks in advance www.baabtra.com | www.massbaab.com |www.baabte.com
  • 47. Want to learn more about programming or Looking to become a good programmer? Are you wasting time on searching so many contents online? Do you want to learn things quickly? Tired of spending huge amount of money to become a Software professional? Do an online course @ baabtra.com We put industry standards to practice. Our structured, activity based courses are so designed to make a quick, good software professional out of anybody who holds a passion for coding.