SlideShare a Scribd company logo
1 of 42
Migrating to
Object-Oriented Programs
Damian Gordon
Object-Oriented Programming
• Let’s start by stating the obvious, if we are designing software
and it is clear there are different types of objects, then each
different object type should be modelled as a separate class.
• Are objects always necessary? If we are just modelling data,
maybe an array is all we need, and if we are just modelling
behaviour, maybe a method is all we need; but if we are
modelling data and behaviour, an object might make sense.
Object-Oriented Programming
• When programming, it’s a good idea to start simple and grow
your solution to something more complex instead of starting
off with something too tricky immediately.
• So we might start off the program with a few variables, and as
we add functionality and features, we can start to think about
creating objects from the evolved design.
Object-Oriented Programming
• Let’s imagine we are creating a program to model polygons in
2D space, each point would be modelled using a pair as an X
and Y co-ordinate (x, y).
•
• So a square could be
– square = [(1,1),(1,2),(2,2),(2,1)]
• This is an array of tuples (pairs).
(1,1)
(2,2)(1,2)
(2,1)
Object-Oriented Programming
• To calculate the distance between two points:
import math
def distance(p1, p2):
return math.sqrt(
(p1[0] – p2[0])**2 + (p1[1] – p2[1])**2)
# END distance
d = √(x2 – x1)2 + (y2 – y1)2
Object-Oriented Programming
• And then to calculate the perimeter:
• Get the distance from:
– p0 to p1
– p1 to p2
– p2 to p3
– p3 to p0
• So we can create an array of the distances to loop through:
– points = [p0, p1, p2, p3, p0]
(1,1)
(2,2)(1,2)
(2,1)
p0 p1
p3 p2
Object-Oriented Programming
• And then to calculate the perimeter:
• So to create this array:
– points = [p0, p1, p2, p3, p0]
• All we need to do is:
– Points = polygon + [polygon[0]]
[(1,1),(1,2),(2,2),(2,1)] + [(1,1)]
(1,1)
(2,2)(1,2)
(2,1)
p0 p1
p3 p2
Object-Oriented Programming
• And then to calculate the perimeter
def perimeter(polygon):
perimeter = 0
points = polygon + [polygon[0]]
for i in range(len(polygon)):
perimeter += distance(points[i], points[i+1])
# ENDFOR
return perimeter
# END perimeter
Object-Oriented Programming
• Now to run the program we do:
>>> square = [(1,1),(1,2),(2,2),(2,1)]
>>> perimeter(square)
>>> square2 = [(1,1),(1,4),(4,4),(4,1)]
>>> perimeter(square2)
Object-Oriented Programming
• So does it make sense to collect all the attributes and methods
into a single class?
• Probably!
Object-Oriented Programming
import math
class Point:
def _ _init_ _(self, x, y):
self.x = x
self.y = y
# END init
Continued 
Object-Oriented Programming
def distance(self, p2):
return math.sqrt(
(self.x – p2.x)**2 + (self.y – p2.y)**2)
# END distance
# END class point
 Continued
Object-Oriented Programming
class Polygon:
def _ _init_ _(self):
self.vertices = []
# END init
def add_point(self, point):
self.vertices.append((point))
# END add_point
Continued 
Object-Oriented Programming
def perimeter(self):
perimeter = 0
points = self.vertices + [self.vertices[0]]
for i in range(len(self.vertices)):
perimeter += points[i].distance(points[i+1])
# ENDFOR
return perimeter
# END perimeter
# END class perimeter
Continued 
Object-Oriented Programming
• Now to run the program we do:
>>> square = Polygon()
>>> square.add_point(Point(1,1))
>>> square.add_point(Point(1,2))
>>> square.add_point(Point(2,2))
>>> square.add_point(Point(2,1))
>>> print("Polygon perimeter is", square.perimeter())
Object-Oriented Programming
Procedural Version
>>> square =
[(1,1),(1,2),(2,2),(2,1)]
>>> perimeter(square)
Object-Oriented Version
>>> square = Polygon()
>>> square.add_point(Point(1,1))
>>> square.add_point(Point(1,2))
>>> square.add_point(Point(2,2))
>>> square.add_point(Point(2,1))
>>> print("Polygon perimeter
is", square.perimeter())
Object-Oriented Programming
• So the object-oriented version certainly isn’t more compact
than the procedural version, but it is clearer in terms of what is
happening.
• Good programming is clear programming, it’s better to have a
lot of lines of code, if it makes things clearer, because someone
else will have to modify your code at some point in the future.
Using Properties
to add behaviour
Object-Oriented Programming
• Imagine we wrote code to store a colour and a hex value:
class Colour:
def _ _init__(self, rgb_value, name):
self.rgb_value = rgb_value
self.name = name
# END _ _init_ _
# END class.
Object-Oriented Programming
• So we would run this as follows:
redcolour = Colour("#FF0000", "Red")
print(redcolour.name, "is", redcolour.rgb_value)
Object-Oriented Programming
• So we would run this as follows:
redcolour = Colour("#FF0000", "Red")
print(redcolour.name, "is", redcolour.rgb_value)
Red is #FF0000
Object-Oriented Programming
• So we would run this as follows:
redcolour = Colour("#FF0000", "Red")
print(redcolour.name, "is", redcolour.rgb_value)
Redcolour.name = “Bright Red”
print(redcolour.name)
Red is #FF0000
Object-Oriented Programming
• So we would run this as follows:
redcolour = Colour("#FF0000", "Red")
print(redcolour.name, "is", redcolour.rgb_value)
Redcolour.name = “Bright Red”
print(redcolour.name)
Red is #FF0000
Bright Red
Object-Oriented Programming
• Sometimes we like to have methods to set (and get) the values
of the attributes, these are called getters and setters:
– set_name()
– get_name()
Object-Oriented Programming
class Colour:
def _ _init_ _(self, rgb_value, name):
self._rgb_value = rgb_value
self._name = name
# END _ _init_ _
def set_name(self, name):
self._name = name
# END set_name
def get_name(self):
return self._name
# END get_name
# END class.
Object-Oriented Programming
class Colour:
def _ _init_ _(self, rgb_value, name):
self._rgb_value = rgb_value
self._name = name
# END _ _init_ _
def set_name(self, name):
self._name = name
# END set_name
def get_name(self):
return self._name
# END get_name
# END class.
The __init__ class is the same as before,
except the internal variable names are
now preceded by underscores to indicate
that we don’t want to access them directly
The set_name class sets the name variable
instead of doing it the old way:
x._name = “Red”
The get_name class gets the name variable
instead of doing it the old way:
Print(x._name)
Object-Oriented Programming
• This works fine, and we can get the colour name in two
different ways:
– print(redcolour._name)
– print(redcolour.get_name())
Object-Oriented Programming
• This works fine, and we can get the colour name in two
different ways:
– print(redcolour._name)
– print(redcolour.get_name())
• The only difference is that we can add additionally
functionality easily into the get_name() method.
Object-Oriented Programming
• So we could add a check into the get_name to see if the name variable
is set to blank:
def get_name(self):
if self._name == "":
return "There is a blank value"
else:
return self._name
# ENDIF;
# END get_name
Object-Oriented Programming
• So now we can run as follows:
redcolour = Colour("#FF0000", "Red")
print(redcolour.get_name())
Object-Oriented Programming
• So now we can run as follows:
redcolour = Colour("#FF0000", "Red")
print(redcolour.get_name())
Red
Object-Oriented Programming
• So now we can run as follows:
redcolour = Colour("#FF0000", "Red")
print(redcolour.get_name())
redcolour._name = ""
print(redcolour.get_name())
Red
Object-Oriented Programming
• So now we can run as follows:
redcolour = Colour("#FF0000", "Red")
print(redcolour.get_name())
redcolour._name = ""
print(redcolour.get_name())
Red
There is a blank value
Object-Oriented Programming
• But that only works if we do this:
– print(redcolour.get_name())
• What if we have a load of code written already that does this?
– print(redcolour._name)
Object-Oriented Programming
• But that only works if we do this:
– print(redcolour.get_name())
• What if we have a load of code written already that does this?
– print(redcolour._name)
• Python provides us with a magic function that takes care of
this, and it’s called property.
Object-Oriented Programming
• So what does property do?
• property forces the get_name() method to be run every
time a program requests the value of name, and property
forces the set_name() method to be run every time a
program assigns a new value to name.
Object-Oriented Programming
• We just add the following line in at the end of the class:
name = property(_get_name, _set_name)
• And then whichever way a program tries to get or set a value,
the methods will be executed.
More details
on Properties
Object-Oriented Programming
• The property function can accept two more parameters, a
deletion function and a docstring for the property. So in total
the property can take:
– A get function
– A set function
– A delete function
– A docstring
Object-Oriented Programming
class ALife:
def __init__(self, alife, value):
self.alife = alife
self.value = value
def _get_alife(self):
print("You are getting a life")
return self.alife
def _set_alife(self, value):
print("You are getting a life {}".format(value))
self._alife = value
def _del_alife(self, value):
print("You have deleted one life")
del self._alife
MyLife = property(_get_alife, _set_alife, _del_alife, “DocStrings:
This is a life property")
# END class.
Object-Oriented Programming
>>> help(ALife)
Help on ALife in module __main__ object:
class ALife(builtins.object)
| Methods defined here:
| __init__(self, alife, value)
| Initialize self. See help(type(self)) for accurate signature.
| -------------------------------------------------------------------
---
| Data descriptors defined here:
| MyLife
| DocStrings: This is a life property
| __dict__
| dictionary for instance variables (if defined)
| __weakref__
| list of weak references to the object (if defined)
etc.

More Related Content

What's hot

Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)Michelle Anne Meralpis
 
Web development with django - Basics Presentation
Web development with django - Basics PresentationWeb development with django - Basics Presentation
Web development with django - Basics PresentationShrinath Shenoy
 
Patterns in Python
Patterns in PythonPatterns in Python
Patterns in Pythondn
 
Introduction To Django
Introduction To DjangoIntroduction To Django
Introduction To DjangoJay Graves
 
Object oriented programming with python
Object oriented programming with pythonObject oriented programming with python
Object oriented programming with pythonArslan Arshad
 
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYAPYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYAMaulik Borsaniya
 
Web Development with Python and Django
Web Development with Python and DjangoWeb Development with Python and Django
Web Development with Python and DjangoMichael Pirnat
 
Modules and packages in python
Modules and packages in pythonModules and packages in python
Modules and packages in pythonTMARAGATHAM
 
A Basic Django Introduction
A Basic Django IntroductionA Basic Django Introduction
A Basic Django IntroductionGanga Ram
 
OOP Introduction with java programming language
OOP Introduction with java programming languageOOP Introduction with java programming language
OOP Introduction with java programming languageMd.Al-imran Roton
 

What's hot (20)

Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)
 
Web development with django - Basics Presentation
Web development with django - Basics PresentationWeb development with django - Basics Presentation
Web development with django - Basics Presentation
 
Python Modules
Python ModulesPython Modules
Python Modules
 
Patterns in Python
Patterns in PythonPatterns in Python
Patterns in Python
 
Introduction To Django
Introduction To DjangoIntroduction To Django
Introduction To Django
 
Object oriented programming with python
Object oriented programming with pythonObject oriented programming with python
Object oriented programming with python
 
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYAPYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
Chapter 07 inheritance
Chapter 07 inheritanceChapter 07 inheritance
Chapter 07 inheritance
 
Javascript
JavascriptJavascript
Javascript
 
Autoboxing And Unboxing In Java
Autoboxing And Unboxing In JavaAutoboxing And Unboxing In Java
Autoboxing And Unboxing In Java
 
Oop concepts in python
Oop concepts in pythonOop concepts in python
Oop concepts in python
 
Web Development with Python and Django
Web Development with Python and DjangoWeb Development with Python and Django
Web Development with Python and Django
 
Modules and packages in python
Modules and packages in pythonModules and packages in python
Modules and packages in python
 
A Basic Django Introduction
A Basic Django IntroductionA Basic Django Introduction
A Basic Django Introduction
 
Django Girls Tutorial
Django Girls TutorialDjango Girls Tutorial
Django Girls Tutorial
 
Oops in Java
Oops in JavaOops in Java
Oops in Java
 
Python list
Python listPython list
Python list
 
Python Functions
Python   FunctionsPython   Functions
Python Functions
 
OOP Introduction with java programming language
OOP Introduction with java programming languageOOP Introduction with java programming language
OOP Introduction with java programming language
 

Viewers also liked

Creating Objects in Python
Creating Objects in PythonCreating Objects in Python
Creating Objects in PythonDamian T. Gordon
 
Python: Multiple Inheritance
Python: Multiple InheritancePython: Multiple Inheritance
Python: Multiple InheritanceDamian T. Gordon
 
Introduction to Python programming
Introduction to Python programmingIntroduction to Python programming
Introduction to Python programmingDamian T. Gordon
 
Python: Third-Party Libraries
Python: Third-Party LibrariesPython: Third-Party Libraries
Python: Third-Party LibrariesDamian T. Gordon
 
Python: The Iterator Pattern
Python: The Iterator PatternPython: The Iterator Pattern
Python: The Iterator PatternDamian T. Gordon
 
The Extreme Programming (XP) Model
The Extreme Programming (XP) ModelThe Extreme Programming (XP) Model
The Extreme Programming (XP) ModelDamian T. Gordon
 

Viewers also liked (11)

Python: Polymorphism
Python: PolymorphismPython: Polymorphism
Python: Polymorphism
 
Creating Objects in Python
Creating Objects in PythonCreating Objects in Python
Creating Objects in Python
 
Python: Manager Objects
Python: Manager ObjectsPython: Manager Objects
Python: Manager Objects
 
Python: Multiple Inheritance
Python: Multiple InheritancePython: Multiple Inheritance
Python: Multiple Inheritance
 
Introduction to Python programming
Introduction to Python programmingIntroduction to Python programming
Introduction to Python programming
 
Object-Orientated Design
Object-Orientated DesignObject-Orientated Design
Object-Orientated Design
 
Python: Design Patterns
Python: Design PatternsPython: Design Patterns
Python: Design Patterns
 
Python: Third-Party Libraries
Python: Third-Party LibrariesPython: Third-Party Libraries
Python: Third-Party Libraries
 
Python: The Iterator Pattern
Python: The Iterator PatternPython: The Iterator Pattern
Python: The Iterator Pattern
 
Python: Access Control
Python: Access ControlPython: Access Control
Python: Access Control
 
The Extreme Programming (XP) Model
The Extreme Programming (XP) ModelThe Extreme Programming (XP) Model
The Extreme Programming (XP) Model
 

Similar to Python: Migrating from Procedural to Object-Oriented Programming

ProgFund_Lecture_4_Functions_and_Modules-1.pdf
ProgFund_Lecture_4_Functions_and_Modules-1.pdfProgFund_Lecture_4_Functions_and_Modules-1.pdf
ProgFund_Lecture_4_Functions_and_Modules-1.pdflailoesakhan
 
Getting Visual with Ruby Processing
Getting Visual with Ruby ProcessingGetting Visual with Ruby Processing
Getting Visual with Ruby ProcessingRichard LeBer
 
PyData NYC 2019
PyData NYC 2019PyData NYC 2019
PyData NYC 2019Li Jin
 
Fast REST APIs Development with MongoDB
Fast REST APIs Development with MongoDBFast REST APIs Development with MongoDB
Fast REST APIs Development with MongoDBMongoDB
 
Class 7a: Functions
Class 7a: FunctionsClass 7a: Functions
Class 7a: FunctionsMarc Gouw
 
CPP13 - Object Orientation
CPP13 - Object OrientationCPP13 - Object Orientation
CPP13 - Object OrientationMichael Heron
 
Business Dashboards using Bonobo ETL, Grafana and Apache Airflow
Business Dashboards using Bonobo ETL, Grafana and Apache AirflowBusiness Dashboards using Bonobo ETL, Grafana and Apache Airflow
Business Dashboards using Bonobo ETL, Grafana and Apache AirflowRomain Dorgueil
 
08-classes-objects.ppt
08-classes-objects.ppt08-classes-objects.ppt
08-classes-objects.pptssuser419267
 
08-classes-objects.ppt
08-classes-objects.ppt08-classes-objects.ppt
08-classes-objects.pptUmooraMinhaji
 
Ray: A Cluster Computing Engine for Reinforcement Learning Applications with ...
Ray: A Cluster Computing Engine for Reinforcement Learning Applications with ...Ray: A Cluster Computing Engine for Reinforcement Learning Applications with ...
Ray: A Cluster Computing Engine for Reinforcement Learning Applications with ...Databricks
 
Functions2.pdf
Functions2.pdfFunctions2.pdf
Functions2.pdfprasnt1
 
Pythonlearn-04-Functions (1).pptx
Pythonlearn-04-Functions (1).pptxPythonlearn-04-Functions (1).pptx
Pythonlearn-04-Functions (1).pptxleavatin
 
An Overview Of Python With Functional Programming
An Overview Of Python With Functional ProgrammingAn Overview Of Python With Functional Programming
An Overview Of Python With Functional ProgrammingAdam Getchell
 
Advanced geoprocessing with Python
Advanced geoprocessing with PythonAdvanced geoprocessing with Python
Advanced geoprocessing with PythonChad Cooper
 
Migrating from matlab to python
Migrating from matlab to pythonMigrating from matlab to python
Migrating from matlab to pythonActiveState
 

Similar to Python: Migrating from Procedural to Object-Oriented Programming (20)

ProgFund_Lecture_4_Functions_and_Modules-1.pdf
ProgFund_Lecture_4_Functions_and_Modules-1.pdfProgFund_Lecture_4_Functions_and_Modules-1.pdf
ProgFund_Lecture_4_Functions_and_Modules-1.pdf
 
Getting Visual with Ruby Processing
Getting Visual with Ruby ProcessingGetting Visual with Ruby Processing
Getting Visual with Ruby Processing
 
Decorators.pptx
Decorators.pptxDecorators.pptx
Decorators.pptx
 
PyData NYC 2019
PyData NYC 2019PyData NYC 2019
PyData NYC 2019
 
Fast REST APIs Development with MongoDB
Fast REST APIs Development with MongoDBFast REST APIs Development with MongoDB
Fast REST APIs Development with MongoDB
 
Class 7a: Functions
Class 7a: FunctionsClass 7a: Functions
Class 7a: Functions
 
CPP13 - Object Orientation
CPP13 - Object OrientationCPP13 - Object Orientation
CPP13 - Object Orientation
 
Business Dashboards using Bonobo ETL, Grafana and Apache Airflow
Business Dashboards using Bonobo ETL, Grafana and Apache AirflowBusiness Dashboards using Bonobo ETL, Grafana and Apache Airflow
Business Dashboards using Bonobo ETL, Grafana and Apache Airflow
 
Python Homework Help
Python Homework HelpPython Homework Help
Python Homework Help
 
OOC in python.ppt
OOC in python.pptOOC in python.ppt
OOC in python.ppt
 
08-classes-objects.ppt
08-classes-objects.ppt08-classes-objects.ppt
08-classes-objects.ppt
 
08-classes-objects.ppt
08-classes-objects.ppt08-classes-objects.ppt
08-classes-objects.ppt
 
Ray: A Cluster Computing Engine for Reinforcement Learning Applications with ...
Ray: A Cluster Computing Engine for Reinforcement Learning Applications with ...Ray: A Cluster Computing Engine for Reinforcement Learning Applications with ...
Ray: A Cluster Computing Engine for Reinforcement Learning Applications with ...
 
Functions2.pdf
Functions2.pdfFunctions2.pdf
Functions2.pdf
 
Pythonlearn-04-Functions (1).pptx
Pythonlearn-04-Functions (1).pptxPythonlearn-04-Functions (1).pptx
Pythonlearn-04-Functions (1).pptx
 
R programmingmilano
R programmingmilanoR programmingmilano
R programmingmilano
 
An Overview Of Python With Functional Programming
An Overview Of Python With Functional ProgrammingAn Overview Of Python With Functional Programming
An Overview Of Python With Functional Programming
 
ProgrammingPrimerAndOOPS
ProgrammingPrimerAndOOPSProgrammingPrimerAndOOPS
ProgrammingPrimerAndOOPS
 
Advanced geoprocessing with Python
Advanced geoprocessing with PythonAdvanced geoprocessing with Python
Advanced geoprocessing with Python
 
Migrating from matlab to python
Migrating from matlab to pythonMigrating from matlab to python
Migrating from matlab to python
 

More from Damian T. Gordon

Universal Design for Learning, Co-Designing with Students.
Universal Design for Learning, Co-Designing with Students.Universal Design for Learning, Co-Designing with Students.
Universal Design for Learning, Co-Designing with Students.Damian T. Gordon
 
Introduction to Microservices
Introduction to MicroservicesIntroduction to Microservices
Introduction to MicroservicesDamian T. Gordon
 
Introduction to Cloud Computing
Introduction to Cloud ComputingIntroduction to Cloud Computing
Introduction to Cloud ComputingDamian T. Gordon
 
Evaluating Teaching: SECTIONS
Evaluating Teaching: SECTIONSEvaluating Teaching: SECTIONS
Evaluating Teaching: SECTIONSDamian T. Gordon
 
Evaluating Teaching: MERLOT
Evaluating Teaching: MERLOTEvaluating Teaching: MERLOT
Evaluating Teaching: MERLOTDamian T. Gordon
 
Evaluating Teaching: Anstey and Watson Rubric
Evaluating Teaching: Anstey and Watson RubricEvaluating Teaching: Anstey and Watson Rubric
Evaluating Teaching: Anstey and Watson RubricDamian T. Gordon
 
Designing Teaching: Pause Procedure
Designing Teaching: Pause ProcedureDesigning Teaching: Pause Procedure
Designing Teaching: Pause ProcedureDamian T. Gordon
 
Designing Teaching: ASSURE
Designing Teaching: ASSUREDesigning Teaching: ASSURE
Designing Teaching: ASSUREDamian T. Gordon
 
Designing Teaching: Laurilliard's Learning Types
Designing Teaching: Laurilliard's Learning TypesDesigning Teaching: Laurilliard's Learning Types
Designing Teaching: Laurilliard's Learning TypesDamian T. Gordon
 
Designing Teaching: Gagne's Nine Events of Instruction
Designing Teaching: Gagne's Nine Events of InstructionDesigning Teaching: Gagne's Nine Events of Instruction
Designing Teaching: Gagne's Nine Events of InstructionDamian T. Gordon
 
Designing Teaching: Elaboration Theory
Designing Teaching: Elaboration TheoryDesigning Teaching: Elaboration Theory
Designing Teaching: Elaboration TheoryDamian T. Gordon
 
Universally Designed Learning Spaces: Some Considerations
Universally Designed Learning Spaces: Some ConsiderationsUniversally Designed Learning Spaces: Some Considerations
Universally Designed Learning Spaces: Some ConsiderationsDamian T. Gordon
 

More from Damian T. Gordon (20)

Universal Design for Learning, Co-Designing with Students.
Universal Design for Learning, Co-Designing with Students.Universal Design for Learning, Co-Designing with Students.
Universal Design for Learning, Co-Designing with Students.
 
Introduction to Microservices
Introduction to MicroservicesIntroduction to Microservices
Introduction to Microservices
 
REST and RESTful Services
REST and RESTful ServicesREST and RESTful Services
REST and RESTful Services
 
Serverless Computing
Serverless ComputingServerless Computing
Serverless Computing
 
Cloud Identity Management
Cloud Identity ManagementCloud Identity Management
Cloud Identity Management
 
Containers and Docker
Containers and DockerContainers and Docker
Containers and Docker
 
Introduction to Cloud Computing
Introduction to Cloud ComputingIntroduction to Cloud Computing
Introduction to Cloud Computing
 
Introduction to ChatGPT
Introduction to ChatGPTIntroduction to ChatGPT
Introduction to ChatGPT
 
How to Argue Logically
How to Argue LogicallyHow to Argue Logically
How to Argue Logically
 
Evaluating Teaching: SECTIONS
Evaluating Teaching: SECTIONSEvaluating Teaching: SECTIONS
Evaluating Teaching: SECTIONS
 
Evaluating Teaching: MERLOT
Evaluating Teaching: MERLOTEvaluating Teaching: MERLOT
Evaluating Teaching: MERLOT
 
Evaluating Teaching: Anstey and Watson Rubric
Evaluating Teaching: Anstey and Watson RubricEvaluating Teaching: Anstey and Watson Rubric
Evaluating Teaching: Anstey and Watson Rubric
 
Evaluating Teaching: LORI
Evaluating Teaching: LORIEvaluating Teaching: LORI
Evaluating Teaching: LORI
 
Designing Teaching: Pause Procedure
Designing Teaching: Pause ProcedureDesigning Teaching: Pause Procedure
Designing Teaching: Pause Procedure
 
Designing Teaching: ADDIE
Designing Teaching: ADDIEDesigning Teaching: ADDIE
Designing Teaching: ADDIE
 
Designing Teaching: ASSURE
Designing Teaching: ASSUREDesigning Teaching: ASSURE
Designing Teaching: ASSURE
 
Designing Teaching: Laurilliard's Learning Types
Designing Teaching: Laurilliard's Learning TypesDesigning Teaching: Laurilliard's Learning Types
Designing Teaching: Laurilliard's Learning Types
 
Designing Teaching: Gagne's Nine Events of Instruction
Designing Teaching: Gagne's Nine Events of InstructionDesigning Teaching: Gagne's Nine Events of Instruction
Designing Teaching: Gagne's Nine Events of Instruction
 
Designing Teaching: Elaboration Theory
Designing Teaching: Elaboration TheoryDesigning Teaching: Elaboration Theory
Designing Teaching: Elaboration Theory
 
Universally Designed Learning Spaces: Some Considerations
Universally Designed Learning Spaces: Some ConsiderationsUniversally Designed Learning Spaces: Some Considerations
Universally Designed Learning Spaces: Some Considerations
 

Recently uploaded

Q4 English4 Week3 PPT Melcnmg-based.pptx
Q4 English4 Week3 PPT Melcnmg-based.pptxQ4 English4 Week3 PPT Melcnmg-based.pptx
Q4 English4 Week3 PPT Melcnmg-based.pptxnelietumpap1
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...Postal Advocate Inc.
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONHumphrey A Beña
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)lakshayb543
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSJoshuaGantuangco2
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxCarlos105
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersSabitha Banu
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfphamnguyenenglishnb
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Celine George
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxAnupkumar Sharma
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Celine George
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Mark Reed
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...JhezDiaz1
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designMIPLM
 

Recently uploaded (20)

Q4 English4 Week3 PPT Melcnmg-based.pptx
Q4 English4 Week3 PPT Melcnmg-based.pptxQ4 English4 Week3 PPT Melcnmg-based.pptx
Q4 English4 Week3 PPT Melcnmg-based.pptx
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginners
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-design
 

Python: Migrating from Procedural to Object-Oriented Programming

  • 2. Object-Oriented Programming • Let’s start by stating the obvious, if we are designing software and it is clear there are different types of objects, then each different object type should be modelled as a separate class. • Are objects always necessary? If we are just modelling data, maybe an array is all we need, and if we are just modelling behaviour, maybe a method is all we need; but if we are modelling data and behaviour, an object might make sense.
  • 3. Object-Oriented Programming • When programming, it’s a good idea to start simple and grow your solution to something more complex instead of starting off with something too tricky immediately. • So we might start off the program with a few variables, and as we add functionality and features, we can start to think about creating objects from the evolved design.
  • 4. Object-Oriented Programming • Let’s imagine we are creating a program to model polygons in 2D space, each point would be modelled using a pair as an X and Y co-ordinate (x, y). • • So a square could be – square = [(1,1),(1,2),(2,2),(2,1)] • This is an array of tuples (pairs). (1,1) (2,2)(1,2) (2,1)
  • 5. Object-Oriented Programming • To calculate the distance between two points: import math def distance(p1, p2): return math.sqrt( (p1[0] – p2[0])**2 + (p1[1] – p2[1])**2) # END distance d = √(x2 – x1)2 + (y2 – y1)2
  • 6. Object-Oriented Programming • And then to calculate the perimeter: • Get the distance from: – p0 to p1 – p1 to p2 – p2 to p3 – p3 to p0 • So we can create an array of the distances to loop through: – points = [p0, p1, p2, p3, p0] (1,1) (2,2)(1,2) (2,1) p0 p1 p3 p2
  • 7. Object-Oriented Programming • And then to calculate the perimeter: • So to create this array: – points = [p0, p1, p2, p3, p0] • All we need to do is: – Points = polygon + [polygon[0]] [(1,1),(1,2),(2,2),(2,1)] + [(1,1)] (1,1) (2,2)(1,2) (2,1) p0 p1 p3 p2
  • 8. Object-Oriented Programming • And then to calculate the perimeter def perimeter(polygon): perimeter = 0 points = polygon + [polygon[0]] for i in range(len(polygon)): perimeter += distance(points[i], points[i+1]) # ENDFOR return perimeter # END perimeter
  • 9. Object-Oriented Programming • Now to run the program we do: >>> square = [(1,1),(1,2),(2,2),(2,1)] >>> perimeter(square) >>> square2 = [(1,1),(1,4),(4,4),(4,1)] >>> perimeter(square2)
  • 10. Object-Oriented Programming • So does it make sense to collect all the attributes and methods into a single class? • Probably!
  • 11. Object-Oriented Programming import math class Point: def _ _init_ _(self, x, y): self.x = x self.y = y # END init Continued 
  • 12. Object-Oriented Programming def distance(self, p2): return math.sqrt( (self.x – p2.x)**2 + (self.y – p2.y)**2) # END distance # END class point  Continued
  • 13. Object-Oriented Programming class Polygon: def _ _init_ _(self): self.vertices = [] # END init def add_point(self, point): self.vertices.append((point)) # END add_point Continued 
  • 14. Object-Oriented Programming def perimeter(self): perimeter = 0 points = self.vertices + [self.vertices[0]] for i in range(len(self.vertices)): perimeter += points[i].distance(points[i+1]) # ENDFOR return perimeter # END perimeter # END class perimeter Continued 
  • 15. Object-Oriented Programming • Now to run the program we do: >>> square = Polygon() >>> square.add_point(Point(1,1)) >>> square.add_point(Point(1,2)) >>> square.add_point(Point(2,2)) >>> square.add_point(Point(2,1)) >>> print("Polygon perimeter is", square.perimeter())
  • 16. Object-Oriented Programming Procedural Version >>> square = [(1,1),(1,2),(2,2),(2,1)] >>> perimeter(square) Object-Oriented Version >>> square = Polygon() >>> square.add_point(Point(1,1)) >>> square.add_point(Point(1,2)) >>> square.add_point(Point(2,2)) >>> square.add_point(Point(2,1)) >>> print("Polygon perimeter is", square.perimeter())
  • 17. Object-Oriented Programming • So the object-oriented version certainly isn’t more compact than the procedural version, but it is clearer in terms of what is happening. • Good programming is clear programming, it’s better to have a lot of lines of code, if it makes things clearer, because someone else will have to modify your code at some point in the future.
  • 19. Object-Oriented Programming • Imagine we wrote code to store a colour and a hex value: class Colour: def _ _init__(self, rgb_value, name): self.rgb_value = rgb_value self.name = name # END _ _init_ _ # END class.
  • 20. Object-Oriented Programming • So we would run this as follows: redcolour = Colour("#FF0000", "Red") print(redcolour.name, "is", redcolour.rgb_value)
  • 21. Object-Oriented Programming • So we would run this as follows: redcolour = Colour("#FF0000", "Red") print(redcolour.name, "is", redcolour.rgb_value) Red is #FF0000
  • 22. Object-Oriented Programming • So we would run this as follows: redcolour = Colour("#FF0000", "Red") print(redcolour.name, "is", redcolour.rgb_value) Redcolour.name = “Bright Red” print(redcolour.name) Red is #FF0000
  • 23. Object-Oriented Programming • So we would run this as follows: redcolour = Colour("#FF0000", "Red") print(redcolour.name, "is", redcolour.rgb_value) Redcolour.name = “Bright Red” print(redcolour.name) Red is #FF0000 Bright Red
  • 24. Object-Oriented Programming • Sometimes we like to have methods to set (and get) the values of the attributes, these are called getters and setters: – set_name() – get_name()
  • 25. Object-Oriented Programming class Colour: def _ _init_ _(self, rgb_value, name): self._rgb_value = rgb_value self._name = name # END _ _init_ _ def set_name(self, name): self._name = name # END set_name def get_name(self): return self._name # END get_name # END class.
  • 26. Object-Oriented Programming class Colour: def _ _init_ _(self, rgb_value, name): self._rgb_value = rgb_value self._name = name # END _ _init_ _ def set_name(self, name): self._name = name # END set_name def get_name(self): return self._name # END get_name # END class. The __init__ class is the same as before, except the internal variable names are now preceded by underscores to indicate that we don’t want to access them directly The set_name class sets the name variable instead of doing it the old way: x._name = “Red” The get_name class gets the name variable instead of doing it the old way: Print(x._name)
  • 27. Object-Oriented Programming • This works fine, and we can get the colour name in two different ways: – print(redcolour._name) – print(redcolour.get_name())
  • 28. Object-Oriented Programming • This works fine, and we can get the colour name in two different ways: – print(redcolour._name) – print(redcolour.get_name()) • The only difference is that we can add additionally functionality easily into the get_name() method.
  • 29. Object-Oriented Programming • So we could add a check into the get_name to see if the name variable is set to blank: def get_name(self): if self._name == "": return "There is a blank value" else: return self._name # ENDIF; # END get_name
  • 30. Object-Oriented Programming • So now we can run as follows: redcolour = Colour("#FF0000", "Red") print(redcolour.get_name())
  • 31. Object-Oriented Programming • So now we can run as follows: redcolour = Colour("#FF0000", "Red") print(redcolour.get_name()) Red
  • 32. Object-Oriented Programming • So now we can run as follows: redcolour = Colour("#FF0000", "Red") print(redcolour.get_name()) redcolour._name = "" print(redcolour.get_name()) Red
  • 33. Object-Oriented Programming • So now we can run as follows: redcolour = Colour("#FF0000", "Red") print(redcolour.get_name()) redcolour._name = "" print(redcolour.get_name()) Red There is a blank value
  • 34. Object-Oriented Programming • But that only works if we do this: – print(redcolour.get_name()) • What if we have a load of code written already that does this? – print(redcolour._name)
  • 35. Object-Oriented Programming • But that only works if we do this: – print(redcolour.get_name()) • What if we have a load of code written already that does this? – print(redcolour._name) • Python provides us with a magic function that takes care of this, and it’s called property.
  • 36. Object-Oriented Programming • So what does property do? • property forces the get_name() method to be run every time a program requests the value of name, and property forces the set_name() method to be run every time a program assigns a new value to name.
  • 37. Object-Oriented Programming • We just add the following line in at the end of the class: name = property(_get_name, _set_name) • And then whichever way a program tries to get or set a value, the methods will be executed.
  • 39. Object-Oriented Programming • The property function can accept two more parameters, a deletion function and a docstring for the property. So in total the property can take: – A get function – A set function – A delete function – A docstring
  • 40. Object-Oriented Programming class ALife: def __init__(self, alife, value): self.alife = alife self.value = value def _get_alife(self): print("You are getting a life") return self.alife def _set_alife(self, value): print("You are getting a life {}".format(value)) self._alife = value def _del_alife(self, value): print("You have deleted one life") del self._alife MyLife = property(_get_alife, _set_alife, _del_alife, “DocStrings: This is a life property") # END class.
  • 41. Object-Oriented Programming >>> help(ALife) Help on ALife in module __main__ object: class ALife(builtins.object) | Methods defined here: | __init__(self, alife, value) | Initialize self. See help(type(self)) for accurate signature. | ------------------------------------------------------------------- --- | Data descriptors defined here: | MyLife | DocStrings: This is a life property | __dict__ | dictionary for instance variables (if defined) | __weakref__ | list of weak references to the object (if defined)
  • 42. etc.