SlideShare a Scribd company logo
Python
Object Oriented Programming
Portland Data Science Group
Created by Andrew Ferlitsch
Community Outreach Officer
July, 2017
Class Definition
• Class defined with the keyword class.
class Node:
….
• Constructor defined with the special reserved name __init__.
class Node:
def __init__( self ):
…
…
Class keyword
Class Name
Keyword to define a method (function)
Reserved name for constructor
Required first parameter, self refers to this instantiated instance of the class.
Class Example
# Base Class definition for Node in Tree/Graph
class Node:
key = None # node data
# constructor: set the node data
def __init__( self, key ):
self.key = key
# Get or Set the node data
def Key( self, key = None ):
if None is key:
return self.key
self.key = key
Start of class definition
Initialization if member variable
Constructor with parameter
Use keyword self to refer to member variable
Define class method
Class Scope
• Parameter to Methods.
class Node:
def myFunc( self, flag )
if flag == True:
• Local to Method
class Node:
def myFunc( self ):
flag = True
• Class Member Variable
class Node:
flag = False
def myFunc( self ):
self.flag = True
• Global Scope
class Node:
def myFunc( self ):
global flag
Parameter ‘flag’
Referenced without qualifier
Referenced without qualifier and not defined as parameter.
Referenced with qualifier self, refers to class variable
When declared with global keyword, all references in method
Will refer to the global (not local) scope of variable.
Method Overloading
• There is NO direct support for method overloading in Python.
• Can be emulated (spoofed) by using Default parameters.
• Example: Setter and Getter
Next() # get the next element
Next(ele) # set the next element
• Without method overloading
# Set Next
def Next( self, next )
self.next = next
# Get Next
def GetNext(self)
return self.next
Must use different function name
Method Overloading using Default Parameter
• A default parameter to a function is where a default value is
specified in the function definition, when the function is called
without the parameter.
• Example: Setter and Getter
# Set of Get Next
def Next( self, next = None )
if next is None:
return self.next
self.next = next
Default Paramter
Get
Set
Operator Overloading
• Built-in operators (+, -, str(), int(), … ) can be overloaded for a
class object in Python.
• Each class has a default implementation for built-in operators.
the default implementations (magic methods) can be overridden to
implement operator overloading.
• Built-in operators are designated using the double dash __name__
convention. Below are some of these magic methods:
__str__ string conversion __add__ + operator
__int__ integer conversion __sub__ - operator
__eq__ == operator __mul__ * operator
__ne__ != operator __divmod__ / and % operator
__lt__ < operator __len__ len() operator
__le__ <= operator __getitem__ [] index operator
Operator Overloading
• Example:
class Node(object):
def __init__(self, name):
self.name = name
def __str__( self ):
return name
def__eq__( self, other ):
return (self.name == other.name)
node = Node( ‘foobar’)
print (str( node ) ) # will print foobar
Override string conversion
Override equal comparison
A full list of magic (special) methods that can be overwritten is available on the python.org website:
https://docs.python.org/3/reference/datamodel.html#special-method-names
Class Inheritance
• Defines a new class that extends a base (superclass).
• The new class (subclass) inherits the methods and member
variables of the base (superclass).
class BinaryTree( Node ):
• Invoking the base (superclass) constructor
Derived (subclass) name Base (superclass) that is inherited
class BinaryTree( Node ):
# Constructor: set the node data and left/right subtrees to null
def __init__( self, key ):
super().__init__( self, key )
Derived (subclass) constructor
Invoke base (superclass) constructor
Good Practice: it's generally considered good practice to have non-inheriting classes explicitly inherit from the "object" class.
Example: class Node: would become class Node(object):

More Related Content

PPTX
Introduce oop in python
PPTX
Python oop class 1
PPTX
Basics of Object Oriented Programming in Python
PDF
Object oriented approach in python programming
PPTX
Advance OOP concepts in Python
PDF
Lecture 01 - Basic Concept About OOP With Python
PPTX
Chapter 05 classes and objects
PPTX
Python OOPs
Introduce oop in python
Python oop class 1
Basics of Object Oriented Programming in Python
Object oriented approach in python programming
Advance OOP concepts in Python
Lecture 01 - Basic Concept About OOP With Python
Chapter 05 classes and objects
Python OOPs

What's hot (20)

PPTX
Python oop - class 2 (inheritance)
PPTX
Introduction to OOP in Python
PDF
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PPTX
Object oriented programming with python
PDF
Python unit 3 m.sc cs
PPTX
Chapter 06 constructors and destructors
PPTX
Basic Concepts of OOPs (Object Oriented Programming in Java)
PPT
Java oops PPT
PPTX
Chapter 07 inheritance
PPTX
class and objects
PPTX
Object-oriented programming
PPTX
Advanced Python : Static and Class Methods
PPTX
Learn Concept of Class and Object in C# Part 3
PDF
Object-oriented Programming-with C#
PPT
11 Using classes and objects
PDF
Object oriented concepts
PPT
C++ classes
PPTX
PDF
Python Programming - VI. Classes and Objects
Python oop - class 2 (inheritance)
Introduction to OOP in Python
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
Object oriented programming with python
Python unit 3 m.sc cs
Chapter 06 constructors and destructors
Basic Concepts of OOPs (Object Oriented Programming in Java)
Java oops PPT
Chapter 07 inheritance
class and objects
Object-oriented programming
Advanced Python : Static and Class Methods
Learn Concept of Class and Object in C# Part 3
Object-oriented Programming-with C#
11 Using classes and objects
Object oriented concepts
C++ classes
Python Programming - VI. Classes and Objects
Ad

Similar to Python - OOP Programming (20)

PPT
Chap 3 Python Object Oriented Programming - Copy.ppt
PPT
Introduction to Python - Part Three
PPTX
Object Oriented Programming in Python.pptx
PDF
Unit_2.0_Functions (1).pdfUnit_2.0_Functions (1).pdf
PDF
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
PPTX
Data Structures and Algorithms in Python
PPTX
Python_Unit_2 OOPS.pptx
PPTX
Unit – V Object Oriented Programming in Python.pptx
PPTX
Python 2. classes- cruciql for students objects1.pptx
PDF
singh singhsinghsinghsinghsinghsinghsinghsinghsingh.pdf
PPT
Lecture topic - Python class lecture.ppt
PPT
Lecture on Python class -lecture123456.ppt
PDF
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
PDF
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
PPTX
Python Unit II.pptx
PPTX
UNIT 3 PY.pptx - OOPS CONCEPTS IN PYTHON
PPT
08-classes-objects.ppt
PPT
08-classes-objects.ppt
Chap 3 Python Object Oriented Programming - Copy.ppt
Introduction to Python - Part Three
Object Oriented Programming in Python.pptx
Unit_2.0_Functions (1).pdfUnit_2.0_Functions (1).pdf
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
Data Structures and Algorithms in Python
Python_Unit_2 OOPS.pptx
Unit – V Object Oriented Programming in Python.pptx
Python 2. classes- cruciql for students objects1.pptx
singh singhsinghsinghsinghsinghsinghsinghsinghsingh.pdf
Lecture topic - Python class lecture.ppt
Lecture on Python class -lecture123456.ppt
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Unit II.pptx
UNIT 3 PY.pptx - OOPS CONCEPTS IN PYTHON
08-classes-objects.ppt
08-classes-objects.ppt
Ad

More from Andrew Ferlitsch (20)

PPTX
AI - Intelligent Agents
PPTX
Pareto Principle Applied to QA
PPTX
Whiteboarding Coding Challenges in Python
PPTX
Object Oriented Programming Principles
PPTX
Python - Installing and Using Python and Jupyter Notepad
PPTX
Natural Language Processing - Groupings (Associations) Generation
PPTX
Natural Language Provessing - Handling Narrarive Fields in Datasets for Class...
PPTX
Machine Learning - Introduction to Recurrent Neural Networks
PPTX
Machine Learning - Introduction to Convolutional Neural Networks
PPTX
Machine Learning - Introduction to Neural Networks
PPTX
Python - Numpy/Pandas/Matplot Machine Learning Libraries
PPTX
Machine Learning - Accuracy and Confusion Matrix
PPTX
Machine Learning - Ensemble Methods
PPTX
ML - Multiple Linear Regression
PPTX
ML - Simple Linear Regression
PPTX
Machine Learning - Dummy Variable Conversion
PPTX
Machine Learning - Splitting Datasets
PPTX
Machine Learning - Dataset Preparation
PPTX
Machine Learning - Introduction to Tensorflow
PPTX
Introduction to Machine Learning
AI - Intelligent Agents
Pareto Principle Applied to QA
Whiteboarding Coding Challenges in Python
Object Oriented Programming Principles
Python - Installing and Using Python and Jupyter Notepad
Natural Language Processing - Groupings (Associations) Generation
Natural Language Provessing - Handling Narrarive Fields in Datasets for Class...
Machine Learning - Introduction to Recurrent Neural Networks
Machine Learning - Introduction to Convolutional Neural Networks
Machine Learning - Introduction to Neural Networks
Python - Numpy/Pandas/Matplot Machine Learning Libraries
Machine Learning - Accuracy and Confusion Matrix
Machine Learning - Ensemble Methods
ML - Multiple Linear Regression
ML - Simple Linear Regression
Machine Learning - Dummy Variable Conversion
Machine Learning - Splitting Datasets
Machine Learning - Dataset Preparation
Machine Learning - Introduction to Tensorflow
Introduction to Machine Learning

Recently uploaded (20)

PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PPTX
Cloud computing and distributed systems.
PDF
CIFDAQ's Market Insight: SEC Turns Pro Crypto
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PPT
Teaching material agriculture food technology
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
Empathic Computing: Creating Shared Understanding
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
PDF
Approach and Philosophy of On baking technology
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PPTX
A Presentation on Artificial Intelligence
“AI and Expert System Decision Support & Business Intelligence Systems”
Chapter 3 Spatial Domain Image Processing.pdf
Cloud computing and distributed systems.
CIFDAQ's Market Insight: SEC Turns Pro Crypto
NewMind AI Weekly Chronicles - August'25 Week I
Understanding_Digital_Forensics_Presentation.pptx
Teaching material agriculture food technology
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Building Integrated photovoltaic BIPV_UPV.pdf
Empathic Computing: Creating Shared Understanding
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
Approach and Philosophy of On baking technology
Per capita expenditure prediction using model stacking based on satellite ima...
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Network Security Unit 5.pdf for BCA BBA.
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Encapsulation_ Review paper, used for researhc scholars
Advanced methodologies resolving dimensionality complications for autism neur...
A Presentation on Artificial Intelligence

Python - OOP Programming

  • 1. Python Object Oriented Programming Portland Data Science Group Created by Andrew Ferlitsch Community Outreach Officer July, 2017
  • 2. Class Definition • Class defined with the keyword class. class Node: …. • Constructor defined with the special reserved name __init__. class Node: def __init__( self ): … … Class keyword Class Name Keyword to define a method (function) Reserved name for constructor Required first parameter, self refers to this instantiated instance of the class.
  • 3. Class Example # Base Class definition for Node in Tree/Graph class Node: key = None # node data # constructor: set the node data def __init__( self, key ): self.key = key # Get or Set the node data def Key( self, key = None ): if None is key: return self.key self.key = key Start of class definition Initialization if member variable Constructor with parameter Use keyword self to refer to member variable Define class method
  • 4. Class Scope • Parameter to Methods. class Node: def myFunc( self, flag ) if flag == True: • Local to Method class Node: def myFunc( self ): flag = True • Class Member Variable class Node: flag = False def myFunc( self ): self.flag = True • Global Scope class Node: def myFunc( self ): global flag Parameter ‘flag’ Referenced without qualifier Referenced without qualifier and not defined as parameter. Referenced with qualifier self, refers to class variable When declared with global keyword, all references in method Will refer to the global (not local) scope of variable.
  • 5. Method Overloading • There is NO direct support for method overloading in Python. • Can be emulated (spoofed) by using Default parameters. • Example: Setter and Getter Next() # get the next element Next(ele) # set the next element • Without method overloading # Set Next def Next( self, next ) self.next = next # Get Next def GetNext(self) return self.next Must use different function name
  • 6. Method Overloading using Default Parameter • A default parameter to a function is where a default value is specified in the function definition, when the function is called without the parameter. • Example: Setter and Getter # Set of Get Next def Next( self, next = None ) if next is None: return self.next self.next = next Default Paramter Get Set
  • 7. Operator Overloading • Built-in operators (+, -, str(), int(), … ) can be overloaded for a class object in Python. • Each class has a default implementation for built-in operators. the default implementations (magic methods) can be overridden to implement operator overloading. • Built-in operators are designated using the double dash __name__ convention. Below are some of these magic methods: __str__ string conversion __add__ + operator __int__ integer conversion __sub__ - operator __eq__ == operator __mul__ * operator __ne__ != operator __divmod__ / and % operator __lt__ < operator __len__ len() operator __le__ <= operator __getitem__ [] index operator
  • 8. Operator Overloading • Example: class Node(object): def __init__(self, name): self.name = name def __str__( self ): return name def__eq__( self, other ): return (self.name == other.name) node = Node( ‘foobar’) print (str( node ) ) # will print foobar Override string conversion Override equal comparison A full list of magic (special) methods that can be overwritten is available on the python.org website: https://docs.python.org/3/reference/datamodel.html#special-method-names
  • 9. Class Inheritance • Defines a new class that extends a base (superclass). • The new class (subclass) inherits the methods and member variables of the base (superclass). class BinaryTree( Node ): • Invoking the base (superclass) constructor Derived (subclass) name Base (superclass) that is inherited class BinaryTree( Node ): # Constructor: set the node data and left/right subtrees to null def __init__( self, key ): super().__init__( self, key ) Derived (subclass) constructor Invoke base (superclass) constructor Good Practice: it's generally considered good practice to have non-inheriting classes explicitly inherit from the "object" class. Example: class Node: would become class Node(object):