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 (20)

Basic data structures in python
Basic data structures in pythonBasic data structures in python
Basic data structures in python
 
JavaScript - Chapter 7 - Advanced Functions
 JavaScript - Chapter 7 - Advanced Functions JavaScript - Chapter 7 - Advanced Functions
JavaScript - Chapter 7 - Advanced Functions
 
Object oriented programming in python
Object oriented programming in pythonObject oriented programming in python
Object oriented programming in python
 
Css selectors
Css selectorsCss selectors
Css selectors
 
09. Java Methods
09. Java Methods09. Java Methods
09. Java Methods
 
XSLT
XSLTXSLT
XSLT
 
Cascading Style Sheets - Part 01
Cascading Style Sheets - Part 01Cascading Style Sheets - Part 01
Cascading Style Sheets - Part 01
 
Java Thread Synchronization
Java Thread SynchronizationJava Thread Synchronization
Java Thread Synchronization
 
Python programming : Files
Python programming : FilesPython programming : Files
Python programming : Files
 
CSS Lists and Tables
CSS Lists and TablesCSS Lists and Tables
CSS Lists and Tables
 
Looping statements
Looping statementsLooping statements
Looping statements
 
Textbox n label
Textbox n labelTextbox n label
Textbox n label
 
Stored procedure
Stored procedureStored procedure
Stored procedure
 
PATTERNS04 - Structural Design Patterns
PATTERNS04 - Structural Design PatternsPATTERNS04 - Structural Design Patterns
PATTERNS04 - Structural Design Patterns
 
C# classes objects
C#  classes objectsC#  classes objects
C# classes objects
 
Data Structures - Lecture 7 [Linked List]
Data Structures - Lecture 7 [Linked List]Data Structures - Lecture 7 [Linked List]
Data Structures - Lecture 7 [Linked List]
 
Datastructures in python
Datastructures in pythonDatastructures in python
Datastructures in python
 
Python pandas Library
Python pandas LibraryPython pandas Library
Python pandas Library
 
Python: Third-Party Libraries
Python: Third-Party LibrariesPython: Third-Party Libraries
Python: Third-Party Libraries
 
Javascript built in String Functions
Javascript built in String FunctionsJavascript built in String Functions
Javascript built in String Functions
 

Viewers also liked

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: Modules and Packages
Python: Modules and PackagesPython: Modules and Packages
Python: Modules and PackagesDamian 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
 
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: Basic Inheritance
Python: Basic InheritancePython: Basic Inheritance
Python: Basic Inheritance
 
Python: Modules and Packages
Python: Modules and PackagesPython: Modules and Packages
Python: Modules and Packages
 
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
 
Python Learn Function with example programs
Python Learn Function with example programsPython Learn Function with example programs
Python Learn Function with example programsGeethaPanneer
 
Advanced geoprocessing with Python
Advanced geoprocessing with PythonAdvanced geoprocessing with Python
Advanced geoprocessing with PythonChad Cooper
 

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
 
Python Learn Function with example programs
Python Learn Function with example programsPython Learn Function with example programs
Python Learn Function with example programs
 
ProgrammingPrimerAndOOPS
ProgrammingPrimerAndOOPSProgrammingPrimerAndOOPS
ProgrammingPrimerAndOOPS
 
Advanced geoprocessing with Python
Advanced geoprocessing with PythonAdvanced geoprocessing with Python
Advanced geoprocessing with 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

1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.MateoGardella
 
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Shubhangi Sonawane
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...christianmathematics
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docxPoojaSen20
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingTeacherCyreneCayanan
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxnegromaestrong
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhikauryashika82
 
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...KokoStevan
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docxPoojaSen20
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxVishalSingh1417
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 

Recently uploaded (20)

Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.
 
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writing
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 

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.